Categories
JavaScript Answers

How to Set a CSS Property of an HTML Element with JavaScript?

Spread the love

Sometimes, we want to set a CSS property of an HTML element with JavaScript.

In this article, we’ll look at how to set a CSS property of an HTML element with JavaScript.

Set a CSS Property of an HTML Element with JavaScript by Setting the style Property

We can set a CSS property of an HTML element with JavaScript by setting a property of the style property.

For instance, we can write:

const element = document.createElement('div');  
element.textContent = 'hello world'  
element.style.backgroundColor = "lightgreen";  
document.body.append(element)

We call document.createElement with 'div' to create a div element.

Then we set the textContent to a string to add some text into the div.

Next, we set the style.backgroundColor property to set its background color.

Any CSS properties with multiple words are in camel case instead of kebab case in CSS.

Then finally, we call document.body.append to append the div into the body element.

Set a CSS Property of an HTML Element with JavaScript by Setting the cssText Property

Another way to set the style of an HTML element with JavaScript is to set the style.cssText property to a string with some CSS styles in it.

For instance, we can write:

const element = document.createElement('div');  
element.textContent = 'hello world'  
element.style.cssText = 'background-color: lightgreen';  
document.body.append(element)

We set element.style.cssText to a string with some CSS styles.

The string just has regular CSS code to set the styles.

Therefore, we get the same result as we had in the previous example.

Conclusion

We can set the CSS styles of an HTML element by setting the style properties within the style property or the style.cssText property to set the CSS text.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *