Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child index of text node in JavaScript or JQuery

I need to figure out how I can the child number of a text element inside of a parent that may have other elements mixed in. Here is an example case:

<p>
    Here is a picture of something:
    <img src="something.png"/>
    Now on to other things, like <span id="highlight">this</span> thing.
</p>

I want to get the <span> element child number, which should be 3 (0-based counting). How do I go about doing this? Using JQuery's index() doesn't work because it only counts the elements and not the text, which would give a 1 in this case. Thank you for your time in looking at this.

like image 220
Spen-ZAR Avatar asked Oct 15 '25 03:10

Spen-ZAR


2 Answers

function getIndex(node) {
    var n = 0;

    while (node = node.previousSibling)
        n++;

    return n;
}

var idx = getIndex(document.getElementById("highlight"));
var span = document.getElementById('highlight'),
    index = Array.prototype.indexOf.call(span.parentNode.childNodes, span);

Array.prototype.indexOf will operate on the NodeList (span.parentNode.childNodes) as though it was an Array and get you the index of your span element.

You'll need a compatibility patch for .indexOf() if you're supporting IE8 and lower.

like image 32
3 revs, 2 users 73%One Trick Pony Avatar answered Oct 17 '25 18:10

3 revs, 2 users 73%One Trick Pony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!