具有相同className的多个div的ClassList.add()-没有jQuery [英] ClassList.add() for multiple divs with same className - No jQuery
问题描述
我有许多具有相同className
( .example )的div.我正在尝试使用普通JavaScript将类添加到每个类的classList中,并成功地做到了,但是仅针对其第一个div具有目标className
的情况,如使用以下代码所示:
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');
}
这将执行以下操作:
<html>
<body>
<div class="example margin">content</div>
<div class="example">content</div>
<div class="example">content</div>
</body>
</html>
但是,我希望这样做:
<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!
推荐答案
您需要循环使用querySelectorAll()
而不是querySelector()
来添加元素,并且没有if
需要使用:
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.
这篇关于具有相同className的多个div的ClassList.add()-没有jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!