How to add a class to DOM element in JavaScript?

JavascriptFront End TechnologyObject Oriented Programming

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');
raja
Published on 02-Dec-2019 06:35:47
Advertisements