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

一个人想着一个人 提交于 2020-12-27 07:16:24

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/49727234/classlist-add-for-multiple-divs-with-same-classname-no-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!