Engin Kurutepe
Engin Kurutepe

Reputation: 6747

Find the DOM element containing a specific offset with jQuery or plain JavaScript

I am paging an HTML page. In order to compute the page break offsets more efficiently, I was wondering if it is possible to get the element containing a certain coordinate offset from the beginning of the page.

Thanks a lot in advance for your help, Cheers!

Upvotes: 2

Views: 1736

Answers (1)

Cristian Sanchez
Cristian Sanchez

Reputation: 32107

You could do something like:

var offset = 100; 
$(document.body).find('[offsetTop = '+offset']');

or

var offset = 100;
$("body *").filter(function () {
   return this.offsetTop == offset;
});

since you said they're all top level elements, the following should also work:

$(document.body).children().filter(function () {
   return this.offsetTop == offset;
});

You can also $(this).offset() to get the offsets. Using the offsetTop property only gets the offset from the parent I believe. But it may not matter since they are all top level elements.

Upvotes: 2

Related Questions