Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 5 - Manipulating CSS

5.1 Modifying CSS With JS

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>
    <title>Change CSS</title>
    <p id="mytext">Hello, world!</p>
    const text = document.getElementById('mytext'); = 'blue'; = '20px';

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.