DOM Manipulation: CSS


DOM Manipulation

DOM stands for Document Object Model. We can change and modify the content of our web document (which is simply the website displayed in the browser) through JavaScript code, without making any changes to our .html file.

Here are some of the ways that we can do it.

Manipulating CSS Styles

In order to change CSS properties we need to select an element and assign it to a variable. Then we follow this pattern: element.style.property = 'value', where element stands for the variable name, property for a CSS property and value for a CSS value.

While single-word properties remain unchanged, multiple-word properties that are hyphenated in CSS need to be converted to camelCase.

Let's select and declare the element that we want to change.

.html

<h1 id="title">Document Title</h1>

.js

const title = document.getElementById('title');

Now let's change the color of our title.

title.style.color = 'lightskyblue';

Document Title

Now let's change the background color of our title.

title.style.backgroundColor = 'grey';

Document Title

Let's change the font family of our title.

title.style.fontFamily = 'cursive';

Document Title

Let's center it.

title.style.textAlign = 'center';

Document Title

Let's give it a border.

title.style.border = '5px solid';

Document Title

Illustration for the DOM Manipulation: CSS
James Harrison on Unsplash

Comments (0)


Be the first to leave a comment