Learn Dynamic HTML With JS
Lesson 1 - HTML JS Relationship
Lesson 2 - HTML DOM
Lesson 3 - Browser BOM
Lesson 4 - Basic Interaction
Lesson 6 - HTTP Requests
Lesson 7 - Form Handling
If you have any pre-defined CSS classes, you can include or exclude them for an element using the following functions:
element.classList.add('className')
: Adds a class to the element.element.classList.remove('className')
: Removes a class from the element.element.classList.toggle('className')
: Toggles a class on the element.For example:
<!DOCTYPE html> <html> <head> <title>Change CSS</title> <style> .highlight { background-color: yellow; } .emphasis { font-weight: bold; color: red; } </style> </head> <body> <p id="myParagraph">Hello, world!</p> </body> <script> const paragraph = document.getElementById('myParagraph'); paragraph.classList.add('highlight'); // Adds the 'highlight' class paragraph.classList.remove('highlight'); // Removes the 'highlight' class paragraph.classList.toggle('emphasis'); // Toggles the 'emphasis' class </script> </html>
In this example, we defined two CSS classes: .highlight
and .emphasis
. We demonstrated how to add (classList.add()
), remove (classList.remove()
), and toggle (classList.toggle()
) classes dynamically using JavaScript. Experiment with different classes to see how they affect the styling of the HTML element.