How to get only Visible Elements using document.getElementsByTag and document.queryselectAll

1k Views Asked by At

I am trying to create a chrome extension that will search for any elements from the web-page.

Currently i am using, var elm = document.getElementsByTagName("input");

This gives me all the elements with tag input.

But sometimes the element is not visible in the screen but present in the source code, for that if i want to filter i try to use the offsetwidth , left, right , height properties

elm.offsetWidth but it always gives 0 so i am not able to filter out.

Also those elements don't have any visibility attributes which i can use.

Is there any other way i can do it using Javascript ?

1

There are 1 best solutions below

0
Patrick Atoon On BEST ANSWER

The trick is to filter for element.offsetWidth !== 0 || element.offsetHeight !== 0 to determine an element is visible.

So, in your example, use this:

var elm = [...document.querySelectorAll('input')]
   .filter(x => x.offsetWidth !== 0 || x.offsetHeight !== 0)