How To Add A Class To A Given Element In JavaScript
Maybe your like
Topic: JavaScript / jQueryPrev|Next
Answer: Use the className Property
If you want to add a class to an HTML element without replacing its existing class, you can do something as shown in the following example:
Example
Try this code » <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Class to an Element Using JavaScript</title> <style> .content{ padding: 20px; border: 2px solid #ccc; } .highlight{ background: yellow; } </style> </head> <body> <div class="content" id="myDiv"> <p>This is a paragraph of text.</p> <button type="button" onclick="addNewClass();">Add Class</button> </div> <script> function addNewClass(){ // Select div element by its id attribute var elem = document.getElementById("myDiv"); elem.className += " highlight"; } </script> </body> </html>In the example above, the addNewClass() function adds a new class highlight to the DIV element that already has a class box without removing or replacing it using the className property.
Alternatively, you can also use the classList property to add/remove classes to an element, like this:
Example
Try this code » <div class="alert info" id="myDiv">Important piece of information!</div> <script> // Selecting element var elem = document.getElementById("myDiv"); elem.classList.add("highlight"); // Add a highlight class elem.classList.remove("alert"); // Remove alert class </script>The classList property is supported in all modern browsers. Not supported in IE prior to version 10.
Related FAQ
Here are some more FAQ related to this topic:
- How to get element by class name in JavaScript
- How to add CSS properties to an element dynamically using jQuery
- How to add attribute to an HTML element in jQuery
Tag » Add Class To Div Id Jquery
-
Jquery Add Class To Element By Id Code Example - Code Grepper
-
.addClass() | JQuery API Documentation
-
JQuery AddClass() Method - W3Schools
-
JQuery Find #ID, RemoveClass And AddClass - Stack Overflow
-
Using JQuery To Add Class To HTML Element
-
JQuery AddClass() Method Tutorial - YogiHosting
-
How To Add / Remove CSS Class Dynamically In JQuery
-
Lesson 1: Understanding ID And Class In CSS
-
Using JQuery Add A New Class To An Element That Already Has A Class
-
Add Class To Clicked Element Using JavaScript - Bobbyhadz
-
JQuery AddClass With HTML Table, Button, Links And List Demos
-
JavaScript Adding A Class Name To The Element - GeeksforGeeks
-
JQuery Selectors Explained: Class Selectors, ID Selectors, And More
-
JavaScript And JQuery By Examples