使用 JavaScript 将一个类添加到多个元素

使用 JavaScript 向多个元素添加一个类

Add a class to multiple Elements using JavaScript

将一个类添加到多个元素:

  1. 使用方法选择元素document.querySelectorAll()
  2. 使用for...of循环遍历元素集合。
  3. 使用该classList.add方法为每个元素添加一个类。

以下是本文示例的 HTML。

索引.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .bg-yellow { background-color: yellow; } </style> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>

这是相关的 JavaScript 代码。

索引.js
const boxes = document.querySelectorAll('.box'); for (const box of boxes) { box.classList.add('bg-yellow'); }

添加类多个元素

我们使用
document.querySelectorAll
方法来选择类为 的所有元素
box

我们使用
for…of
循环遍历元素集合。

On each iteration, we use the
classList.add
method to add a class to the element.

If the class is already present on the element, it won’t get added twice.

You can pass as many classes to the add() method as necessary.

index.js
const boxes = document.querySelectorAll('.box'); for (const box of boxes) { box.classList.add( 'bg-yellow', 'second-class', 'third-class' ); }

Similarly, if you need to remove one or more classes, you can use the
classList.remove() method.

index.js
const boxes = document.querySelectorAll('.box'); for (const box of boxes) { box.classList.add( 'bg-yellow', 'second-class', 'third-class' ); box.classList.remove( 'second-class', 'third-class' ); }
The querySelectorAll method takes one or more selectors, so we are able to select elements with multiple different classes, ids, etc.

Here is an example that uses the method to get a collection of elements with 3
different classes.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .bg-yellow { background-color: yellow; } </style> </head> <body> <div class="box1">Box 1</div> <div class="box2">Box 2</div> <div class="box3">Box 3</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const boxes = document.querySelectorAll('.box1, .box2, .box3'); for (const box of boxes) { box.classList.add('bg-yellow', 'second-class', 'third-class'); box.classList.remove('second-class', 'third-class'); }

We passed 3 different selectors to the querySelectorAll method by separating
them with commas.

您可以通过在值前加上id前缀来将 an 传递给方法,例如
id##my-id