We can add a style to an element by using the style
property of an object.
To style an element, first we have to get the element that we want to style.
We can do this easily with document.querySelector
, which takes a string with any CSS selector.
For instance, if we have the following div:
<div class='foo'>
foo
</div>
We can get div by the class. We can write:
const el = document.querySelector('.foo');
to get the div element with the class foo
that we have above.
Then we can set the styles according to the properties list below at MDN.
The CSS and the JavaScript equivalents are listed on that page.
For instance, if we want to set the color of the content inside the div we have above, we can set the color
property as follows:
el.style.color = 'green';
The code above sets the color
property of the style
property to 'green'
.
This will turn the text in the div green.
We can do the same thing with any property name in the ‘JavaScript’ column at this page.
We can set the style of an element is simple with JavaScript. However, we shouldn’t do that too frequently so that our browsers won’t be too busy setting styles for elements with JavaScript.