📜  ClassList - Javascript (1)

📅  最后修改于: 2023-12-03 14:40:06.262000             🧑  作者: Mango

ClassList - Javascript

The classList property is a JavaScript object that represents a collection of the class attributes of an HTML element. It provides various methods to manipulate the class attribute of an element with ease.

Properties
classList.length

This property returns the number of classes of an element.

Methods
classList.add(className1[, className2, ...])

This method adds one or more class names to an element. If a class name already exists, it will not add the class again.

const el = document.querySelector('.example');
el.classList.add('foo', 'bar');
classList.remove(className1[, className2, ...])

This method removes one or more class names from an element.

const el = document.querySelector('.example');
el.classList.remove('foo', 'bar');
classList.toggle(className[, force])

This method adds a class name if it is not present on an element or removes it if it is present. If the force parameter is truthy, it adds the class name; otherwise, it removes it.

const el = document.querySelector('.example');
el.classList.toggle('foo');
classList.contains(className)

This method checks if an element has a specific class name.

const el = document.querySelector('.example');
if (el.classList.contains('foo')) {
  console.log('foo class is present');
}
classList.replace(oldClassName, newClassName)

This method replaces a class name with a new one.

const el = document.querySelector('.example');
el.classList.replace('foo', 'new-foo');
Browser compatibility

The classList property is supported in all major browsers, including Chrome, Firefox, Safari, Edge, and Internet Explorer 10+.