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?

2
  • Simply assign to the .onclick property instead of calling addEventListener? Commented Jan 16, 2019 at 4:42
  • your div have no parent ? Commented Jan 16, 2019 at 4:46

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.