Jump to content

Query selector problem


Go to solution Solved by kicken,

Recommended Posts

I'm fiddling around on a W3 page in order to achieve a better understanding of current JS practices.

Goal: if ANY of several paragraphs are clicked, send an alert message.

//var a = 
document.querySelectorAll("p").addEventListener('click', fn);
function fn(){ 
//var i;for (i = 0; i < a.length; i++) { 
//alert(this.innerHTML);
//}
alert(222);
} 

I've managed to achieve success with querySelector to push out the alert for paragraph #1, but the querySelectorAll implementation seems to be causing me trouble.

Insight and solutions to approaching this properly, please.

Edited by phppup
Typos
Link to comment
https://forums.phpfreaks.com/topic/316962-query-selector-problem/
Share on other sites

  • Solution

querySelectorAll returns a NodeList, which does not have an addEventListener method.  Assigning an event handler to a collection of elements is a jQuery thing.  In plain JavaScript, you have to loop over the elements in the collection and assign the event handler to each one individually, or attach it to a common parent element.

document.querySelectorAll("p").forEach((e) => {
	e.addEventListener('click', fn);
});

 

  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.