JavaScript DOM Manipulation - Modifying Element Styles

DOM manipulation in JavaScript allows you to dynamically change the appearance of HTML elements on a web page. One common way to do this is by modifying the element's styles. In this guide, we'll explore how to manipulate the styles of HTML elements using JavaScript and provide examples to illustrate their usage.

Accessing Element Styles

You can access and modify the styles of an HTML element using the style property. This property provides access to inline styles applied to the element. Here's an example:

<div class="box" id="myBox">This is a box</div>
const myBox = document.getElementById('myBox'); = 'lightblue'; = 'red'; = '20px';

In this example, we change the background color, text color, and font size of the "myBox" element by directly modifying its styles.

Modifying Multiple Styles at Once

You can modify multiple styles at once using the style.cssText property, which allows you to set a complete list of styles in a single string. Here's an example:

<div class="box" id="myBox2">This is another box</div>
const myBox2 = document.getElementById('myBox2'); = 'background-color: lightgreen; color: blue; font-size: 18px;';

In this example, we change the background color, text color, and font size of "myBox2" by setting all the styles in one cssText string.

Using CSS Classes

An organized approach is to define styles in CSS classes and then apply those classes to elements. Here's an example:

.highlight {
background-color: yellow;
color: black;
<div class="box" id="myBox3">This is a box</div>
const myBox3 = document.getElementById('myBox3');

In this example, we define a CSS class named "highlight" and add it to the "myBox3" element to change its styles.


Modifying element styles in the DOM is a powerful way to create dynamic and interactive web pages. By accessing and manipulating element styles using JavaScript, you can respond to user interactions and update the appearance of your web content on the fly, providing a better user experience.

Happy coding with DOM manipulation in JavaScript!