1
<div className="example" style="top:10;left:10"></div>  //array 1
<div className="example" style="top:100;left:100"></div>  //array 2
<div className="example" style="top:145;left:101"></div>  //array 3
<div className="example" style="top:120;left:150"></div>  //array 4
<div className="example" style="top:145;left:160"></div>  //array 5
<div className="example" style="top:10;left:120"></div>  //array 6
<div className="example" style="top:15;left:100"></div>  //array 7


<script>
var x = $(".example")[0].position();  //array 1 [0]
alert("Top: " + x.top + " Left: " + x.left);
</script>

I need to get the position of a certain div

but when I run the code I get error

VM163:1 Uncaught TypeError: $(...)[0].position is not a function(…)

1
  • 1
    $(".example").eq(0).position() Commented May 15, 2016 at 17:06

2 Answers 2

4

Try this: http://jsbin.com/liliwarogo/1/edit

var x = $($(".example")[0]).position();  //array 1 [0]
alert("Top: " + x.top + " Left: " + x.left);

Basically, if you do $(".example")[0] it's not a jQuery element anymore, so position() doesn't exists. I wrapped everything up in jQuery again, to get the position() function.

Of course, the optimal solution would be something like this: $(".example:eq(0)").position()

Sign up to request clarification or add additional context in comments.

1 Comment

I absolutely agree, I wanted to explain why $(".example")[0].position() doesn't work - that making [0] you're not operating with jQuery anymore. $(".example").eq(0) is of course the best solution, but it doesn't explain why the original approach didn't work. Besides, I personally prefer $(".example:eq(0)"). I've updated my original answer accordingly to your comment.
1

This solution only use JavaScript.

var x = document.getElementsByClassName("example")[0].getBoundingClientRect();
alert("Top: " + x.top + " Left: " + x.left);

Here is the Jsbin example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.