0

I need to find an elements current position within the DOM (preferably when clicked).

With jQuery, I get it if I know the position beforehand:

$('li').get(3);

But there are times when I rely on $(this) to get the current position:

HTML:

http://jsfiddle.net/JBjeg/

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
</ul>

JS:

 $('li').click(function(){

     // this does not work
    console.log($(this).get());

    // this does, but I won't know which is clicked
    console.log($('li').get(3));

});

What's the best way for me to get the current position? Preferably as a number, so I can use it elsewhere.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375

4 Answers4

3

You can use index to get the number of clicked element.

$(this).index();

Index will be Starting from 0

$('li').click(function(){
     // this does not work
    console.log($(this).get());   
    // Will get index
    console.log($(this).index());
    // this does, but I won't know which is clicked
    console.log($('li').get(3)); 
});

Update

According to your comment in the last answer

If you want image related to index of the clicked li you may try this

var index = $(this).index(); // Get index
var img = $("img").get(index); // image selector may vary

Fiddle

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
1

You can use .index()

Search for a given element from among the matched elements.

Example

$("li").index('ul')
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

You're looking for the index() method:

$('li').click(function(){
    console.log($(this).index());
});

(updated demo fiddle)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

You can use index:

$('li').click(function() {
    console.log($(this).index());
});

And also, you can use $.each:

$('li').each(function(index) {
    console.log([$(this), index]);
});
casraf
  • 21,085
  • 9
  • 56
  • 91
  • That's great. Say I've got a list of images elsewhere, how would I get the matching index? (I click the second `li`, I need the second `img`) –  May 21 '14 at 13:02
  • say `index` holds the index, you just call `$('img').get(index)` – casraf May 21 '14 at 13:05
  • @tmyie See my answer, I have updated according to your comment! – Dhaval Marthak May 21 '14 at 13:06
  • Thanks! The only problem is that it returns undefined on the matching item: http://jsfiddle.net/JBjeg/4/ –  May 21 '14 at 13:10
  • 1
    .get() returns the actual DOM element, rather than jQuery object. You need to recast it: `$($('p').get(i)).show()` ([example](http://jsfiddle.net/JBjeg/5/)) – casraf May 21 '14 at 13:23
  • That's great. How come I have to recast it? –  May 21 '14 at 13:29
  • Because `$('p')` retrieves a jQuery object, which has `.show()` as one of its functions in its prototype. `$('p').get(0)` will retrieve the pure DOM element, not it's jQuery manifestation. It will only have DOM properties, such as `.style.display`. If you recast it, you will be using its jQuery reference. – casraf May 21 '14 at 13:30