How to select elements based on their position?


Short Description:
I want to select an element based on it’s position on the viewport.

Example use-case:
for example consider the below image. When I navigate with keyboard, I want to move to Block D after Block A in mobile viewport. But which block is placed below Block A is not fixed. It can change based on the gap below Block A, or if additional blocks come in to picture (say Block E), then it might come below Block A.

Is there a way to select a block/element which is placed below Block A or any of the blocks for that matter.

Again, I am aware of selecting via class names & navigating via DOM Order. But need help to navigate dynamically placed elements.

enter image description here


Suppose your page is structured like this:

  1. Gap between the top of the page and the top of Block A : 10px
  2. Block A height: 100px
  3. Gap between the bottom of Block A and the next Block (via margin-bottom for example): 10px

So the distance between the top of the document and the top of the unknown block after Block A is 120px. we call it "secondBlockDistanceFromTop".

Now you have to get a list of all possible blocks after Block A, you could do that by giving all of them a ".block" class and use "document.querySelectorAll". We store this array in "blocks" variable.

Every DOM object’s distance from the top of the document can be calculated by this formula:

 let blockDistanceFromTop=el.getBoundingClientRect().top +  window.scrollY

now you can use an array iteration method on the "blocks" array and check if each element’s "blockDistanceFromTop" equals "secondBlockDistanceFromTop"

Answered By – Erfan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published