使用 TypeScript 检查元素是否包含类

使用 TypeScript 检查元素是否包含类

Check if an Element contains a class using TypeScript

在 TypeScript 中检查一个元素是否包含一个类:

  1. 选择特定元素。
  2. 使用该classList.contains()方法检查元素是否包含该类。
  3. true如果该类包含在元素的类列表中,则该方法返回。

以下是本文示例的 HTML。

索引.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body> <div id="box" class="salmon">Hello world</div> <script src="./src/index.ts"></script> </body> </html>

这是相关的 TypeScript 代码。

源代码/index.ts
const box = document.getElementById('box'); if (box?.classList.contains('salmon')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); }

我们使用
document.getElementById
方法来选择元素。

The method returns a null value if an element with the provided id does not
exist in the DOM, so we had to use the
optional chaining (?.)
operator to make sure the box variable does not store a null value.

The optional chaining (?.) operator short-circuits if the reference is nullish (null or undefined).

The
classList.contains
method returns a boolean value – true if the class is contained in the
element’s class list and false otherwise.

We could have also used a simple if statement that serves as a
type guard.

index.ts
const box = document.getElementById('box'); if (box != null) { if (box.classList.contains('salmon')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); } }

We explicitly check that the box variable does not store a null value before
accessing its classList property.

Once we enter the if block, TypeScript knows that the type of the box variable is HTMLElement, not HTMLElement | null.

If you need to add classes to an element or remove classes from an element, use
the classList.add and classList.remove methods.

src/index.ts
const box = document.getElementById('box'); box?.classList.add('class-1', 'class-2'); box?.classList.remove('class-2', 'class-3');

He
classList.add()
method adds one or more classes to an element.

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

On the other hand, the classList.remove() method can be used to remove one or
more classes from an element.

If any of the classes isn’t present on the element, the remove() method
ignores the class and does not throw an error.