I want to get a top element (Element Object) from the viewport of a web page with JavaScript. (If any part of the top boundary of an html element is visible on the viewport that element is within the viewport)
The approach I came up was:
- Find all the elements with
document.body.getElementsByTagName("*")
- Check if each element is in the viewport with How can I tell if a DOM element is visible in the current viewport?
- Get the element with the lowest
el.getBoundingClientRect().top
value from the matching elements of the step 2
If there are many element at the same level (Eg: parents and children), matching any of them would be ok.
This seems to be too much code for a small requirement. Is there a shorter approach?