skyline3000 skyline3000 - 3 months ago 7
Javascript Question

How to determine DOM position of element in a series of elements when clicked

In this scenario, I have a series of list items each of which has a corresponding content area. When clicking a list item, a corresponding content area is manipulated (i.e., if the first list item is clicked, then the first content section would be manipulated).

<ul>
<li>List item</li>
<li>List item</li>
<li>List item</li>
</ul>

<div>
<section>Content section</section>
<section>Content section</section>
<section>Content section</section>
</div>


My oldschool way of doing this was giving each list item and section an id, such as "li1", "li2", etc. and "section1", "section2", etc. I would then parse the integer off the id of the element that was clicked and manipulate the corresponding section.

Is there a way to determine this without needing extra id attributes? E.g., if I click the 3rd list item and know that is the 3rd, I can use
document.querySelector('div:nth-child(3)')
to manipulate the third content section. My question is how to know it was the 3rd element in a series that was clicked to begin with.

My first-thought solution was something like this:

var target = e.target;
var parent = e.target.parentNode;

for (var i in parent.childNodes) {
if (parent.childNodes[i].nodeType == 1 && parent.childNodes[i] == target) {
// found it... i+1
}
}


This seems like a rather expensive operation compared to just using IDs, especially if there were many more list items and content sections. I'm hoping there is some node attribute that will give me the correct DOM position that I haven't yet found.

Modern browser-only solutions welcomed. Thanks.

Answer

Update 2016

Well I've run into this issue again nearly 5 years later only this time I used a much simpler solution using a built-in Array method:

var index = Array.prototype.indexOf.call(event.target.parent.children, event.target);