Issue
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>
Solution
It results in an error because document.querySelectorAll() returns a NodeList, not an Array; and indexOf – Array.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:
Answered By - David Thomas Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.