JavaScript Code

How to add a classname to div using JavaScript?


Tutorials using JS

Problem Statement

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