Which of the following methods can be used to add a class to an HTML element in JavaScript?OptionsaddClass()element.addClass()element.classList.add()element.addClassName()
Question
Which of the following methods can be used to add a class to an HTML element in JavaScript?OptionsaddClass()element.addClass()element.classList.add()element.addClassName()
Solution
The correct method to add a class to an HTML element in JavaScript is element.classList.add().
Here's how you can do it:
- First, you need to select the HTML element. You can do this using various methods like
getElementById(),getElementsByClassName(),getElementsByTagName(), orquerySelector(). For example:
let element = document.getElementById('myElement');
- Once you have the element, you can add a class to it using
classList.add()method. For example, if you want to add a class named 'newClass', you would do it like this:
element.classList.add('newClass');
This will add the 'newClass' to the 'myElement' HTML element.
The other methods mentioned in the options such as addClass(), element.addClass(), and element.addClassName() are not standard JavaScript methods for adding a class to an HTML element.
Similar Questions
Which keyword is used to define a class in JavaScript?OptionsclassobjectprototypeClass
How can you add an HTML attribute to an HTML element using JavaScript?1 pointBy invoking the setAttribute method on a given element.By invoking the getAttribute method on a given element.By invoking the createAttribute method on a given element.
Which attribute is used to provide additional information about an HTML element?Optionsclassstyletitleid
What is use of class attribute in HTML?
Which attribute is used to provide additional information about an HTML element?Optionsclassidstyletitle
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.