简体   繁体   中英

Get the offset position of a table using its index with jQuery

I have two tables in a page. And i print their top co-ordinates using jQuery's $.offset().top .

$("table").offset().top 

prints the first table offsets. Doesn't $("table") select all the tables? How does it print just the first table's co-ordinates?

And when i try to print the second table's offset position using $("table")[1] , it says $("table")[1].offset is undefined

Jsfiddle link is at, http://jsfiddle.net/JfGVE/805/

Note: I can get the results using table's id but i am looking for a solution that uses table's index to get its offset

You can't use jQuery methods on DOM elements.

A jQuery object contains DOM elements, and you were trying to use the jQuery method .offset() on one of the DOM elements in the jQuery object.

Use the .eq() method in order to access a jQuery object by its index instead:

$("table").eq(1).offset().top;

(As a side-note, the .eq() method's index is zero-based, so .eq(1) is the second element.)


It's also worth mentioning that you can wrap the DOM element $("table")[1] with $() in order to use it as a jQuery object:

$($("table")[1]).offset().top

jquery docs for offset():

Get the current coordinates of the first element in the set of matched elements, relative to the document.

says it all

You can either iterate over the tables and store their offset in an array. When you access the table as $("table")[1], it becomes a javascript object. In order to get the offset for this element you can use any of the following:

$("table").eq(1).offset().top

or 

$($("table")[1]).offset().top

This is because .offset() is a jquery function and not a javascript funtion.

您可以使用.eq()代替。

console.log("the first table offset is " +$("table").eq(1).offset().top)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM