With each click, classList.toggle () will add the CSS class if it does not exist in the classList array and return true. WebIn JavaScript, there are some approaches to add a class to an element. Please mail your requirement at [emailprotected] Duration: 1 week to 2 week. Corrections causing confusion about using over , Identification of the dagger/mini sword which has been in my family for as long as I can remember (and I am 80 years old). Let's try to do that. You can also add a class to the body element when an event occurs, e.g. Thanks for contributing an answer to Stack Overflow! In JavaScript, using the addEventListener() method: Click a

element to change the text color: Another example on how to change the color of an element: Click to copy text from one input field to another: How to assign an "onclick" event to the window object: onclick is a DOM Level 2 (2001) feature. To add multiple classes to the element pass the multiple class names separated by spaces to the setAttribute method.

To remove a class from an element, you just need to set the className property to a string containing the class name that you want to remove. Tip: Learn more about the className property in our JavaScript Reference. We have an onclick attribute inside our button opening tag ready to execute a showMore() function, so let's write the function. Add Class To A Body Element In JavaScript Using ClassName Property, Add Class To A Body Element In JavaScript Using ClassList Property, Adding Classes To Multiple Elements At Once, Conclusion Add Class To Body JavaScript, Get The Child Element By Class In JavaScript, Display A Hidden div Element On Mouseover In JavaScript, Cannot Read Property appendChild of Null JavaScript, cannot read property firstChild of null Error In JavaScript, How To Clear The Value Of TextArea Element In JavaScript, Check If Object Is Empty In JavaScript 9 Methods, Check If A Set Contains An Object In JavaScript, Check If A JavaScript Object Contains A Function, Access Object With Space In Key In JavaScript, Check If A JavaScript Object Is Of Type Set, Get A Data Attribute From The Event Object In JavaScript. For more information, and if your wondering why .live() was bad deprecated take a look at jQuery .live() vs .on() review. So we need to write it in a JavaScript file, or in the HTML file inside a