Home > OS >  How to get an index of event element in a NodeList with .indexOf
How to get an index of event element in a NodeList with .indexOf

Time:09-22

I need to know an index of a target element. My code throws an error. Does not .indexOf() work for NodeList?

const divs = document.querySelectorAll('div');

function isFirst(event) {
  // Fine
  console.log(event.target == divs[0]);
  
  // But... Error! Why?
  console.log(divs.indexOf(event.target));
}

divs.forEach(e => e.addEventListener('click', isFirst));
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>

CodePudding user response:

It results in an error because document.querySelectorAll() returns a NodeList, not an Array; and indexOfArray.prototype.indexOf() – is a method of an Array, not a NodeList, and as such doesn't have access to the indexOf() method.

You could instead convert the iterable NodeList to an Array using an Array literal along with the spread syntax:

const divs = document.querySelectorAll('div');

function isFirst(event) {
  // Fine
  console.log(event.target == divs[0]);
  
  // But... Error! Why?
  console.log([...divs].indexOf(event.target));
}

divs.forEach(e => e.addEventListener('click', isFirst));
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>

References:

  • Related