How to Add a Class to a Given Element in JavaScript

  311 views   6 months ago Javascript

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>

 

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles