Mark As Completed Discussion

Manipulating Styles

One of the key aspects of working with the Document Object Model (DOM) is the ability to modify the CSS styles of DOM elements. This allows us to customize the appearance of elements on a web page.

To manipulate the styles of an element, we can use the style property of the element's JavaScript object. The style property provides access to various CSS properties that we can modify.

Let's say we have an element with the class myElement, and we want to modify its background color, font size, add a border, and update the text content. We can do this using the following code:

JAVASCRIPT
1// Let's start by selecting an element
2const element = document.querySelector('.myElement');
3
4// Change the background color of the element
5element.style.backgroundColor = 'blue';
6
7// Change the font size of the element
8element.style.fontSize = '24px';
9
10// Add a border to the element
11element.style.border = '1px solid red';
12
13// Update the text content of the element
14element.textContent = 'Hello, World!';

In this example, we first select the element using the querySelector method and the appropriate CSS selector. Then, we use the style property to modify the desired CSS properties.

By manipulating the styles of DOM elements, we can create dynamic and visually appealing web pages. Whether it's changing colors, sizes, or adding animations, JavaScript provides the flexibility to customize the styles based on user interactions and other events.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment