jQuery index() in vanilla javascript

As per the jQuery api, the complementary operation to .get(), which accepts an index and returns a DOM node, .index() can take a DOM node and returns an index. Suppose we have a simple unordered list on the page:

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

.index() will return the position of the first element within the set of matched elements in relation to its siblings:

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

We get back the zero-based position of the list item:

Index: 1

I just want to know, how can we do the same using JavaScript??

Answers:

Answer

You can build your own function :

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;
}

Demonstration (open the console)

Answer

I've modified Travis J answer to not include TextNodes and made a function out of it.

You can run it in the console and see (on stackoverflow).

Classic way:

function getNodeindex( elm ){ 
    var c = elm.parentNode.children, i = 0;
    for(; i < c.length; i++ )
        if( c[i] == elm ) return i;
}

// try it
var el = document.getElementById("sidebar");
getNodeindex(el);

With ES2015:

function getNodeindex( elm ){ 
    return [...elm.parentNode.children].findIndex(c => c == elm)
    // or
    return [...elm.parentNode.children].indexOf(elm)
}

Demo:

const getNodeindex = elm => [...elm.parentNode.children].indexOf(elm)
<button onclick="console.log(  getNodeindex(this)  )">get index</button>
<button onclick="console.log(  getNodeindex(this)  )">get index</button>
<button onclick="console.log(  getNodeindex(this)  )">get index</button>


I also want to point to another thread on the same matter, which has a great answer (for people seeking older IE support)

Answer

No loops needed, call Array#indexOf on .parentElement.children:

const element = document.querySelector('#baz');

[].indexOf.call(element.parentElement.children, element);
// => 2

You can even call it on a random list of elements, just like you can in jQuery:

const list = document.querySelectorAll('li');
const element = document.querySelector('#baz');

[].indexOf.call(list, element);
// => 2
Answer

You can find this information out by going up the dom tree using previousElementSibling and incrementing.

var getElementIndex(element) {
    if (!element) {
        return -1;
    }
    var currentElement = element,
        index = 0;

    while(currentElement.previousElementSibling) {
        index++;
        currentElement = currentElement.previousElementSibling;
    }
    return index
}

getElementIndex(document.getElementById('#bar'));

here is the browser support for previousElementSibling:

https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/previousElementSibling

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.