简体   繁体   中英

ClassList.add() for multiple divs with same className - No jQuery

I have a number of divs with the same className ( .example ). I'm attempting to add classes to the classList of each of them using vanilla JavaScript, and successfully do so, but only for the first div of which possesses the targeted className , as shown using the following code:

<html>
 <body> 
  <div class="example">content</div>
  <div class="example">content</div>
  <div class="example">content</div>
 </body>
</html>


var example = document.querySelector('.example');

if (className = ('.example')){
  example.classList.add('margin');
}

this does the following:

<html>
 <body> 
  <div class="example margin">content</div>
  <div class="example">content</div>
  <div class="example">content</div>
 </body>
</html>

However, I wish to do this:

<html>
 <body> 
  <div class="example margin">content</div>
  <div class="example margin">content</div>
  <div class="example margin">content</div>
 </body>
</html>

Hopefully I've provided enough information for you, thank you in advance!

You need to loop through the elements using querySelectorAll() and not querySelector() to add classes and there's no if you need to use:

 // Select all the elements with example class. var examples = document.querySelectorAll('.example'); // Loop through the elements. for (var i = 0; i < examples.length; i++) { // Add the class margin to the individual elements. examples[i].classList.add('margin'); }
 <div class="example">content</div> <div class="example">content</div> <div class="example">content</div>

The code above is well commented. Let me know if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM