问题
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