Js: Loop Through List Of Divs To Add Event By Onclick?
test
test
test
If I have a list of divs and want the font size to increase to 20px when clicking each one,Solution 1:
You have to iterate over all the elements. You can use onclick like the following way:
let elements = document.querySelectorAll('div');
for (var x = 0; x < elements.length; x++) {
elements[x].onclick = function(){
this.style.fontSize = "20px";
}
};<div>test</div><div>test</div><div>test</div>Please see addEventListener vs onclick for differences.
Solution 2:
You could define font sizes in a CSS Class and add those classes to all the divs. On click, just update the CSS class's font size javascript. This won't need a loop.<< Edit: CSS updation might need a loop ..! >>
You can refer the following tutorial for this
http://www.shawnolson.net/a/503/altering_css_class_attributes_with_javascript.html
Hope that helps..
Solution 3:
If you just don't want a loop, check for a click on the page, then look at the event's target (the thing that was clicked):
document.addEventListener("click", function(e) {
if (e.target.tagName == "DIV") {
e.target.style.fontSize = "20px";
}
})<div>test</div><div>test</div><div>test</div>
Post a Comment for "Js: Loop Through List Of Divs To Add Event By Onclick?"