Skip to main content

Tedshd's Dev note

JavaScript - jQuery index() in JavaScript

Table of Contents

# JavaScript - jQuery index() in JavaScript

## JavaScript

function indexInParent(node) {
    var children = node.parentNode.childNodes;
    var num = 0;
    for (var i=0; i<children.length; i++) {
         if (children[i]==node) return num;
         if (children[i].nodeType==1) num++;
    }
    return -1;
}

## Example

<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>
  • jQuery
alert($('#bar').index());
  • javaScript
var el = document.getElementById("bar");
function indexInParent(node) {
    var children = node.parentNode.childNodes;
    var num = 0;
    for (var i=0; i<children.length; i++) {
         if (children[i]==node) return num;
         if (children[i].nodeType==1) num++;
    }
    return -1;
}
alert(indexInParent(el));

Demo

Refer - jQuery .index() in javascript