JavaScript Code


How to add a classname to div using JavaScript?


Tutorials using JS

Add a classname to div using JavaScript

In this tutorial, you shall learn how to add a classname to the existing classnames of a div element using JavaScript.

Solution

To add a classname to the existing classnames of a div element using JavaScript, we can use Element.classList property. Call add() method on the classList property and pass the required classname as argument.

divElement.classList.add('full');

Program

When user clicks on the Click me button, we get the div element with the id myDiv, and add the classname card to the existing classnames (if any) using classList property.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button><br>
<div id="myDiv">About</div>
<div>Terms</div>

<style>
.card {
  box-shadow: 2px 2px 4px green;
  border-radius: 10px;
  display: inline;
  padding: 10px;
}
</style>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
    //get the div element
    const myDiv = document.getElementById("myDiv");
    //add classname for div
    myDiv.classList.add("card");
});
</script>

</body>
</html>


Copyright @2022