Changing Inline Styles

Most of the CSS changes we'll do with JavaScript involve adding or removing classes. However, there may be situations where we want to directly alter an element's inline styles.

Since inline styles are just another HTML attribute (along with id, class, etc.) we can use setAttribute() and change the style attribute.

Assuming the presence of <p id='text'>Some stuff</p> in an HTML document, the following code demonstrates one way of working with inline styles using JavaScript.

const text = document.getElementById('text')

text.setAttribute('style', `
background-color: #ddd;
color: darkgrey;
font-size: 40px;
`)

console.log(text.getAttribute('style'))

A multiline string literal has been used here for readability and is completely optional.

Another favourite method among web developers is to use dot notation and access a special style property automatically created for each JavaScript HTML element object. To avoid confusing these special properties with other JavaScript object properties, we'll use the setAttribute() approach when manipulating inline styles in this course.