Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get target element's (numeric) dom hierarchy javascript

Tags:

javascript

dom

No library solutions, please, though if you know of one that does this, I'm happy to take a look at how they do it. Not terribly concerned with fall-backs and cross browser support.

I have a hierarchy (that will change):

<body>
    <div></div>
    <div>
        <div></div>
        <div></div>
        <div>
            <a>Click Me!</a>
        </div>
    </div>
</body>

I have an event listener on <a>Click Me!</a> and get an event object back. That much works. YEY!

I want the event.target dom hierarchy numerical index. basically, [0][1][2][0] (though it would probably return as an array, [0,1,2,0], and that's okay with me).

I know this can be done with iterating through the parent elements. I'm trying to avoid that iteration, if possible.

EDIT Redacting my last edit as an act of idiocy.

like image 287
Randy Hall Avatar asked Feb 20 '26 03:02

Randy Hall


1 Answers

A way to get an index without explicit iteration is to use the array indexOf method.

Here is what it would look like, e being your event:

function getIndex(e){
  var t=e.target;
  return Array.prototype.indexOf.call(t.parentNode.childNodes,t);
}

There's a number of gotchas with this technique. First, indexOf is only supported by the most recent browsers. Second, you need the call trick because a NodeList is not an array. Third, childNodes might return more nodes than expected and then you'll have to filter by node type.

To get the whole hierarchy index, just rince and repeat as you climb up the DOM hierarchy with parentNode.

For the record, e.target is not cross-browser either, but I see this is what you're already using.

[Update] The full code, using children instead of childNodes:

function getIndex(e) {
var index=[],
    t=e.target;

while (t!==document.body) {
    index.unshift(Array.prototype.indexOf.call(t.parentElement.children,t));
    t=t.parentElement;
}
return index;
}
like image 126
Christophe Avatar answered Feb 22 '26 00:02

Christophe



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!