简体   繁体   English

ClassList.add() 用于具有相同 className 的多个 div - 没有 jQuery

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

I have a number of divs with the same className ( .example ).我有许多具有相同className ( .example ) 的 div。 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:我正在尝试使用 vanilla JavaScript 将类添加到每个类的 classList 中,并且成功地这样做了,但仅对于拥有目标className的第一个 div ,如使用以下代码所示:

<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:您可以通过元素需要循环使用querySelectorAll()而不是querySelector()来添加类,有没有if你需要使用:

 // 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.如果您有任何问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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