views:

48

answers:

2

for example, how to detect the index of the li elem in it's parent ul?

+5  A: 
<ul>
    <li>this</li>
    <li>is</li>
    <li>ul</li>
</ul>

<ul>
    <li>this</li>
    <li>is</li>
    <li>another</li>
    <li>ul</li>
</ul>

if you have something like above, you could do jQuery as:

$(function(){
  $('li').click(function(){ alert('the index is '+$(this).index()) })

})

this will alert the index of the li element based on its parent ul

more on index() here.

Reigel
i don't know this method of jQuery, thanks~
lovespring
+1  A: 

In non-IE browsers, whitespace between elements are considered text nodes (which is not the case in IE), which affects the index of subsequent elements. To give the same results in all browsers, the function below by default filters out whitespace nodes, and has an optional parameter to include them if that's what you want:

function indexOfNode(node, includeWhitespace) {
    var index = 0, n = node;
    while ( (n = n.previousSibling) ) {
        if (includeWhitespace || n.nodeType != 3 || !/^\s*$/.test(n.data)) {
            ++index;
        }
    }
    return index;
}
Tim Down