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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With