How to add class to element in Javascript
By FoxLearn 1/14/2025 3:02:22 AM 148
In JavaScript, you can add a class to an HTML element using the classList property and the add() method.
This method adds the specified class to the element without affecting any existing classes.
document.getElementById("myElement").classList.add("myClass")
This code selects the element with the ID "myElement" and adds the class "myClass" to its classList
.
How to add a class to a html element in Javascript?
For example, Add a class to an element by its id
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Add Class Example</title> </head> <body> <div id="myElement">Javascript add class to element</div> <button onclick="addClassToElement()">Add Class</button> <script> function addClassToElement() { // Get the element by its ID var element = document.getElementById('myElement'); // Add the 'new-class' to the element's class list element.classList.add('new-class'); } </script> </body> </html>
For example, Add a class to an element by its class
name or other selector
// Add class to all elements with a certain class name document.querySelectorAll('.some-class').forEach(function(element) { element.classList.add('new-class'); // js add class });
classList.add('className')
adds a new class without removing any existing classes.
If the class is already present on the element, it won't be added again. You can also add multiple classes at once: element.classList.add('class1', 'class2');
.
- How to convert voice to text in Javascript
- LET vs VAR in JavaScript Variable Declarations
- How to add voice commands to webpage in Javascript
- How to capture an image in javascript
- How to Build Your Own JavaScript Library
- How to reverse a string properly in Javascript
- How to bypass 'Access-Control-Allow-Origin' error with XMLHttpRequest
- What is Hoisting in JavaScript