PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to get an index of event element in a NodeList with .indexOf

 October 15, 2022     dom, ecmascript-6, javascript     No comments   

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:

  • Array.prototype.indexOf().
  • Array literals.
  • Spread syntax.


Answered By - David Thomas
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing