0
<div id="div">
    <h1 id="1">Index 1</h1>
    <h1 id="2">Index 2</h1>
    <h1 id="3">Index 3</h1>
</div>
// Something like this, but this doesn't work.
const div = document.getElementById('div').childNodes;
const _h1 = document.getElementById('2');
for (const i of div) {
    if (i == _h1) {
        console.log(div.indexOf(i);
    }
}

I have a div which has some child nodes. I also have an element _h1. How can we get the index of the _h1 element if it exists inside the div assuming we are unknown to the quantity of the child nodes of the div.

Any help is highly appreciated.

Thank you

  • 1
    Don't forget to check the [second](https://stackoverflow.com/a/23528539/5625547) and [third](https://stackoverflow.com/a/39395069/5625547) answers since there' more up-to-date then the accepted one! – 0stone0 May 05 '21 at 11:13
  • ok, got it. Thank you! –  May 05 '21 at 11:15

0 Answers0