javascript - Get the offset position of a table using its index with jQuery - Stack Overflow

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

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, /

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

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/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

Share Improve this question edited Dec 2, 2015 at 15:07 Josh Crozier 242k56 gold badges400 silver badges313 bronze badges asked Dec 2, 2015 at 4:01 user2879704user2879704 0
Add a ment  | 

4 Answers 4

Reset to default 2

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 bees 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.

You can use .eq() instead.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745618198a4636361.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信