How to Add a Class to a Given Element in 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">
<meta charset="utf-8">
<title>Add Class to an Element Using JavaScript</title>
        padding: 20px;
        border: 2px solid #ccc;
        background: yellow;
    <div class="content" id="myDiv">
        <p>This is a paragraph of text.</p>
        <button type="button" onclick="addNewClass();">Add Class</button>
    function addNewClass(){
        // Select div element by its id attribute
        var elem = document.getElementById("myDiv");
        elem.className += " highlight";