How to add a class to an element in Javascript?

Member

by natalia , in category: JavaScript , 2 years ago

How to add a class to an element in Javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@natalia You can use classList.add() method to add a new class to an element in Javascript, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<html>
<head>
    <meta charset="utf-8"/>
</head>
<body>
<button class="button">Button</button>
</body>
<script>
    document.querySelector('.button').classList.add('btn')
</script>
</html>

Member

by roberto , a year ago

@natalia 

To add a class to an element in JavaScript, you can use the classList property of the element and the add() method:

1
element.classList.add("className");


Here, element is the reference to the HTML element, and "className" is the name of the class you want to add. For example:

1
2
var element = document.getElementById("myDiv");
element.classList.add("newClass");


In this example, the class "newClass" is added to the element with the ID of "myDiv".