How to Add a Class to a Given Element
Read the tutorial and learn the two suggested methods of creating a JavaScript function that will add a class to the <div> element and solve your problem.
The class attribute is used to assign one or more class names to an element for styling or scripting purposes. If you want to create a JavaScript function that will add a class to the <div> element, there are some methods of doing it in JavaScript.
The .className property
The <kbd class="highlighted">className</kbd> property of the Element interface is used for getting and setting the value of the given element's class attribute.
First, put an id on the element to get a reference:
Javascript element id
<div id="divId" class="someClass">
<p>Add new classes</p>
</div>Then use the .className to add a class:
Javascript add className property
<!DOCTYPE html>
<html>
<body>
<div id="divId" class="someClass ">
<p>Add new classes</p>
</div>
<script>
let cName = document.getElementById("divId");
cName.className += " otherClass";
alert(cName.className);
</script>
</body>
</html>When concatenating strings with .className, ensure the new class string starts with a space (e.g., += " otherClass"). Without it, the new class merges directly with the existing one (e.g., someClassotherClass), breaking both classes.
The .add() method
The <kbd class="highlighted">add()</kbd> method of the DOMTokenList interface is used to add the given token to the list. This method is also used to add a class name to the specified element.
Javascript add method
<!DOCTYPE html>
<html>
<body>
<div id="divId" class="someClass ">
<p>Add new classes</p>
</div>
<script>
function addClass() {
let cName = document.getElementById("divId");
cName.classList.add("addNewClass");
alert(cName.classList);
}
addClass();
</script>
</body>
</html>