Youss
Youss

Reputation: 4212

Jquery index doesn't work for child nodes

I would like to index everything in document and then call it by its index. The HTML:

<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
</ul>

Alert to get index:

alert('Index: ' + $('#foo').index());

The problem is that it alerts number 0 for both ul and #foo. I understand the logic of this but I need them in order, so the ul should count for 0 and #foo should be 1.

What can I try to get this type of indexing? I tried prevAll() but that gives the same result.

PS Please not this is just an example, in reality the code should work on large documents.

Example code

Upvotes: 1

Views: 335

Answers (2)

Tharabas
Tharabas

Reputation: 3422

index() without arguments will look for the index of an element within it's parent. But you can call it with an argument to surpass that.

Suppose we're working on your example

<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
</ul>

A solution could look like this:

$('ul, li').index($('ul'))   // => 0
$('ul, li').index($('#foo')) // => 1
$('ul, li').index($('#bar')) // => 2

You can even do this programatically:

$('ul, li').each(function(i) {
  console.log(this.tagName + (!!this.id ? " #" + this.id : "") + " = " + i)
})

// UL     => 0
// LI#foo => 1
// LI#bar => 2

Just be aware, that $(selector).index(element) will return the index of the element within the Nodes matched by selector.

Hope that helps.

Upvotes: 1

Blender
Blender

Reputation: 298046

You could do something like this:

$.fn.tree_index = function() {
    var index = -1;

    $(this).parents().each(function() {
        index += $(this).index() + 1;
    });

    return index;
}

alert('Index: ' + $('#foo').tree_index());

Upvotes: 1

Related Questions