phppup Posted June 11, 2023 Share Posted June 11, 2023 (edited) 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 June 11, 2023 by phppup Typos Quote Link to comment Share on other sites More sharing options...
Solution kicken Posted June 11, 2023 Solution Share Posted June 11, 2023 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); }); 1 Quote Link to comment Share on other sites More sharing options...
phppup Posted June 11, 2023 Author Share Posted June 11, 2023 (edited) @kicken Understood. I saw similar solutions but couldn't understand why they were using such a convoluted approach. Now it makes sense. Thanks for the explanation. I'll give it a try. Edited June 11, 2023 by phppup Forgot item Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.