How to add a class to an element using JavaScript?The class attribute can be used in CSS to do some tasks for the elements with the corresponding class name. In this article, we are discussing how to add a class to an element using JavaScript. In JavaScript, there are some approaches to add a class to an element. We can use the .className property or the .add() method to add a class name to the particular element. Now, let's discuss the approaches to add a class to an element. Using .className propertyThe .className property sets the class name of an element. This property can be used to return the value of the class attribute of an element. We can use this property to add a class to an HTML element without replacing its existing class. To add multiple classes, we have to separate their name with space such as"class1 class2". If a class is already declared for an element, and we need to add a new class name to the same element then it should be declared by inserting a space before writing the new class name otherwise, it will overwrite the existing class name. It can be written as follows: In the above code, we have inserted a space before newClass. SyntaxThe commonly used syntax of this property to set or to return the class name is given below. To set the class name To return the class name The example of using the .className property is given as follows. Example - Adding the class nameIn this example, we are using the .className property for adding the "para" class to the paragraph element having id "p1". We are applying the CSS to the corresponding paragraph using the class name "para". We have to click the given HTML button "Add Class" to see the effect. Test it NowOutput After clicking the given button, the output will be - In the next example, we are getting the name of the class by using the .className property. Example - Getting the class nameIn this example, we are using the .className property to get the class names of the paragraph element having id = "p1". We have to click the given HTML button "Get Class name" to see the effect. Test it NowOutput After clicking the given button, the output will be - Using add() methodNow, let's see the second approach of adding the class name using JavaScript. We can use the add() method to add a class name to the particular element. SyntaxExampleIn this example, we are using the add() method to add a class name to the paragraph element having id = "p1". We have to click the given HTML button "Add Class" to see the effect. Test it NowOutput After clicking the given button, the output will be - |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India