JavaScript Add Class To Div
Last Updated : Mar 11, 2024
IN - JavaScript | Written & Updated By - Pragati
In this article we will show you the solution of JavaScript add class to div, a read-only property on elements, element.classList returns the element's class attributes in DOMTokenList form. The class list can then be manipulated using this method.
By using classList instead of an element. className, you can access a string representing the classes of the elements.
The element's class attribute is represented by a DOMTokenList. In the absence of a class attribute, it returns a DOMTokenList with the length property set to 0, i.e., a DOMTokenList with no tokens.
A document (HTML document) can be manipulated using DOM (Document Object Model). DOM elements have a class name that can be set and accessed in this article. Each HTML element is defined as an object in DOM.
Element class names are set with the .className property. The HTML element's existing class can be modified by adding a class using this property.
When adding multiple classes, they need to be separated by a space, such as "class1 class2".
Step By Step Guide On JavaScript Add Class To Div :-
<!DOCTYPE html> <html> <head><center> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .mystyle { width: 130%; padding: 30px; background-color: coral; color: white; font-size: 30px; box-sizing: border-box; } </style> </head> <body> <p>TalkersCode Button to Add Example</p> <button onclick="myFunction()">Click here</button> <div id="myDIV"> This is the DIV element. </div> <script> function myFunction() { var element = document.getElementById("myDIV"); element.classList.add("mystyle"); } </script> </body> </html>
- This command tells the browser which version of HTML we are using. The beginning of an HTML document contains HTML tags.
- A project's heading can be explained using the <head> tag.
- It is used when an external style sheet has a full URL or a path relative to the current page and is referenced with the Step-by-step tag.
- Then stylesheet and head close using </stylesheet> </head>
- Then we create paragraph using <p> tag.
- To add up and down arrows, we use an ng-class directive in conjunction with the onclick directive.
- The script tag explains the source code we used for the javascript google API to run and the file we used that or the code.
- After that </script></body></html> and code should be executed after closing all tags.
Conclusion :-
An element with a class name can be assigned certain tasks with the class attribute in CSS.
A class can be added to an element in JavaScript in a few different ways. It is possible to use the .className property or the .add() method to add a class name to a particular element.
I hope this article on JavaScript add class to div helps you and the steps and method mentioned above are easy to follow and implement.