Computer >> Computer tutorials >  >> Programming >> Javascript

How do I add a class to a given element using Javascript?


To add a class to a DOM element, you first need to find it using a querySelector like querySelector, getElementById, etc. Then you need to add the class. For example, if you have the following HTML −

Example

<!DOCTYPE html>
<html>
   <head></head>
   <body>
      <p id="para">This is some text</p>
   </body>
</html>

You can find the element using either of the following 2 ways −

querySelector

let myPara = querySelector('#para')[0];

getElementById

let myPara = getElementById('para');

Then you can add a class to this element using −

let myPara = getElementById('para');
myPara.classList.add('myClass');