Styling elements using the style attribute in JavaScript

Let's now learn how to add CSS styles to elements. This is done by changing the attribute style. For example, to change the color, you need to build the following chain: elem.style.color, and assign the desired color value to it.

Let's look at an example. Let's say we have this element:

<p id="elem">text</p>

Let's make this element red:

let elem = document.querySelector('#elem'); elem.style.color = 'red';

Given a div and a button. On click on the button, set a width, height, and border to the div.

Hyphenated properties

Properties that are hyphenated, such as font-size, are converted to camelCase. That is, font-size will become fontSize:

elem.style.fontSize = '20px';

Given a div with text and a button. On click on the button, set the div's font size to 20px, as well as the top border and background.

Exception

The property float is an exception, as it is special in JavaScript. For it, you should write cssFloat:

elem.style.cssFloat = 'right';

Given a list ul and a button. On button click add property float with value left to li tags.

enru