1
 <div>test</div>
 <div>test</div>
 <div>test</div>

If I have a list of divs and want the font size to increase to 20px when clicking each one, I know I can do the following:

let elements = document.querySelectorAll('div');

for (var x = 0; x < elements.length; x++) {
  elements[x].addEventListener('click', () => {event.target.style.fontSize = "20px"}
}

Is there a way to iterate through the listen and add an onclick rather than doing it with the addEventListener way instead? Also, if there is, is one preferred over the other?

Raymon Opie
  • 237
  • 1
  • 9

3 Answers3

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.

Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    straight forward ...thanks. I'm aware of the benefit `addEventListener` has to allowing multiple events attached but besides that, is one way preferred over the other? – Raymon Opie Jan 16 '19 at 04:55
  • @RaymonOpie, Please visit https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick – Mamun Jan 16 '19 at 04:57
0

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..

sr56
  • 711
  • 5
  • 4
0

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>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79