The textbook I’m using to learn JavaScript uses the following code to display an alert dialogue whenever a user clicks on a paragraph:
var paras = document.getElementsByTagName("p");
for (var i=0; i<paras.length; i++) {
paras[i].onclick = function() {
alert("You clicked on a paragraph.");
}
}
I don’t see the reason to loop through all the p elements, but instead identify them and simply attach the onclick event handler to it. Like this:
var paras = document.getElementByTagName('p');
paras.onclick = alert("You clicked on a paragraph.");
Doesn’t that do the same thing? Why is it necessary to loop through the p elements?
No, that absolutely does not do the same thing:
alert()statement, not a function as in your example. (Doesn’t really matter because it won’t work anyway.)Now there is a way to handle the clicks with just one event handler, but I’ll let you keep reading your book 🙂
edit — To elaborate on point 2, this:
is a function call. Its value will be whatever is returned from calling that function. Thus,
sets the “onclick” property of the object that “paras” refers to, and it sets it to the value returned from
alert()(which is probably alwaysundefined).As in the sample code from your book, things like “onclick” handlers need to be functions. That’s what’s going on in the middle of your sample code: the “onclick” property of each individual
<p>DOM element is being set to a function. Inside that function is the call toalert().