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 04 Answers
Reset to default 2You 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)