Which of the following methods can be used to add a class to an HTML element in JavaScript?Optionselement.addClassName()element.addClass()addClass()element.classList.add()
Question
Which of the following methods can be used to add a class to an HTML element in JavaScript?Optionselement.addClassName()element.addClass()addClass()element.classList.add()
Solution
The correct method to add a class to an HTML element in JavaScript is element.classList.add().
Here's a step-by-step guide on how to use 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(). You just need to pass the class name as a string argument to this method. For example:
element.classList.add('myClass');
- Now, the HTML element with the id 'myElement' will also have the class 'myClass'. You can check this by inspecting the element in the browser's developer tools.
The other methods mentioned in the question (element.addClassName(), element.addClass(), addClass()) are not standard JavaScript methods for adding a class to an HTML element.
Similar Questions
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 keyword is used to define a class in JavaScript?OptionsclassobjectprototypeClass
Which attribute is used to provide additional information about an HTML element?Optionsclassstyletitleid
Which attribute is used to provide additional information about an HTML element?Optionsclassidstyletitle
What is use of class attribute in HTML?
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.