1

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)

enter image description here enter image description here

The approach I came up was:

  1. Find all the elements with document.body.getElementsByTagName("*")
  2. Check if each element is in the viewport with How can I tell if a DOM element is visible in the current viewport?
  3. 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?

Sampath Liyanage
  • 4,776
  • 2
  • 28
  • 40
  • Can you use the solution here [How much of an element is visible in viewport?](https://stackoverflow.com/q/33859522/2430549) and simply check for first element that is `100%` in viewport? – HoldOffHunger Aug 17 '21 at 15:50
  • Hi I think your answer in this [question](https://stackoverflow.com/questions/1350581/how-to-get-an-elements-top-position-relative-to-the-browsers-viewport). Please check I hope it is useful – Komeyl Aug 17 '21 at 15:53

0 Answers0