Get child index of text node in JavaScript or JQuery - Stack Overflow

admin2025-04-19  0

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.

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.

Share Improve this question asked May 8, 2013 at 23:52 Spen-ZARSpen-ZAR 8287 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3
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 patibility patch for .indexOf() if you're supporting IE8 and lower.

jQuery has a .contents() method that grabs all children, including text nodes (and ment nodes). You can use that to grab the span at index 3:

$('p').contents()[3]; // your span!

Then you can use .index to get the index based on a node reference:

var pContents = $('p').contents();
var span = pContents[3];  // your span
var spanIndex = pContents.index(span); // 3

http://jsfiddle/yERLu/1

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745077422a283651.html

最新回复(0)