How to add class to element in Javascript
By Tan Lee Published on Dec 18, 2024 269
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 use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Toolbox Admin Responsive Tailwind CSS Admin Template
Nov 20, 2024
Portal HTML Bootstrap
Nov 13, 2024
Focus Admin Dashboard Template
Nov 18, 2024