Q:

How to Add a Class to a Given Element in JavaScript

0

How to Add a Class to a Given Element in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

<!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:

<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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Find the Max and Min Values of an Array in ... >>
<< How to Get Portion of URL Path in JavaScript...