Show Output
<!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>