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
Modifying CSS dynamically is crucial for modern, user-centric web development, ensuring flexibility and adaptability. It enhances the user experience by providing visual feedback, improving accessibility, and maintaining a cohesive design across various devices.
JavaScript provides a comprehensive set of tools to modify CSS dynamically, thereby making your application smooth, attractive, and engaging.
To modify CSS, you can select elements using several methods:
document.getElementById()
: Selects an element by its ID.const element = document.getElementById('myElement');
document.getElementsByClassName()
: Selects elements by their class name and returns a collection of elements.const elements = document.getElementsByClassName('myClass');
document.getElementsByTagName()
: Selects elements by their tag name and returns a collection of elements.const elements = document.getElementsByTagName('p');
document.querySelector()
: Selects the first element that matches a CSS selector.const element = document.querySelector('.myClass');
document.querySelectorAll()
: Selects all elements that match a CSS selector. This returns a NodeList.const elements = document.querySelectorAll('p');
Once you've selected an element, you can use the style
property to change its CSS. The style
property is an object where each CSS property is a key.
For example:
<!DOCTYPE html> <html> <head> <title>Change CSS</title> </head> <body> <p id="mytext">Hello, world!</p> </body> <script> const text = document.getElementById('mytext'); text.style.color = 'blue'; text.style.fontSize = '20px'; </script> </html>
In this example, we applied CSS styles (color
and fontSize
) to the HTML element with the ID mytext
. Experiment with different styles to see how they affect the appearance of the HTML element.