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>
<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.