Change Element class Using JavaScript
Change Element class Using JavaScript : You can use JavaScript to change the element’s class simply using the className attribute. You can also use this to add multiple classes to the element. Here in this tutorial we are going to explain how to change the element’s class using JavaScript. You can use our online editor to run the demo.
How to Change Element class Using JavaScript ?
JavaScript Replace(Change) All Classes By One(Single) Class
You can use className attribute to replace all classes by one class as below –
JavaScript className : Syntax
Syntax to change the className using the pure JavaScrpt is as Below –
JavaScript className Syntax:
document.getElementById("ElementId").className = "NewClass"; |
Where ElementId is id selector of the element. NewClass is class name you want to add.
JavaScript className : Example
JavaScript className Syntax:
<script type='text/javascript'> function changeClass(){ document.getElementById("myId").className = "YellowBg"; } </script> |
The above example changes the class of element which have id “myId”. It will add the new class YellowBg to the element. If you run the above example it will produce the output something like this –
More Examples
Let’s have look over more example and demo here.
JavaScript Add Additional Class
If you want to add additional class in the existing element without removing/affecting the existing classes, use the className method as in below example –
JavaScript Append className : Example
<script type='text/javascript'> function appendClass(){ document.getElementById("myId").className += " borderBlack"; } </script> |
The above example will append the given class “borderBlack” to the element. Make sure you add a blank space before the class name so that it is not collapsed with other existing class name.
Advertisements
Add Comment
đź“– Read More
- 1. Capitalize first letter of string in JavaScript
- 2. JavaScript Add String Newline Character
- 3. JavaScript Redirect to a page after few seconds on Button Click