Getting all link regions from web page

Dear community,

I need to obtain all link regions from document. Currently I’m doing this in 2 steps:

  1. Create a link list by Iterating through the “<a>” elements in DOM and collecting their rects
  2. Remove from the list items, that are somehow hidden (low z-index, overflow, hidden parent, etc)

Second step is very complex - we need to check many clauses in order to decide, whether links are visible or not. Moreover, links can have one or more child elements like DIV or IMG, etc, and these elements also affect the resulting links regions. Calculating regions for partially hidden links is also a non-trivial task. :sob:

I wonder if there’s more simple way to do this. Perhaps some API or another idea I’m missing? :rocket:

I would assume https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect is very helpful in this task, as calculating the visibility of a rectangle is pretty simple.

Further I’d recommend to pre-filter your list of anchors by doing something like querySelectorAll("a:not([hidden])"), which will give you a list of anchors without the hidden attribute.

Thanks Martin, however this is not as easy as it might be looking. The getBoundingClientRect() method returns just rectangle.

Suppose you have one link in scrolling area being displayed partially, plus some elements with higher z-order (defined implicitly or instantiated from parent) covering this link in different variations, so you’re getting a complex region. You’ll need to take into account all the positioning details (and I suspect, there are a bunch of different cases). It looks like if you would decide to rewrite the rendering tree. :thinking:

You could sample the viewport with document.elementFromPoint(x, y).
(If that returns an <iframe> you will propably want to test its .contentDcocument too)