tutorialstonight logo

Javascript DOM STYLE

How to Style Using Javascript?

One of the biggest uses of javascript is in styling HTML elements dynamically. Using javascript we can add or remove CSS property to any element.

You can set color, background, border, animation, font style, text alignments, width, height, padding, position and so on.

CSS should always be preferred for styling of elements. Only in case we need some dynamic action we can use javascript.

In this section we will learn various methods of styling elements using javascript.

Changing Element Style

To Change style of an elements:

  1. Select the element, example - getElementById
  2. Use style property to the element
  3. Then concatenate CSS property to that and assign value in quotes.


document.getElementById("id1").style.css_property = "value"

Let's change the color of the <p> tag in example below.

Example: setting style using javascript

Run the code

In the above example we set color to the paragraph directly using javascript, but we can also set style or change style of any element when an event is fired. Events could be anything like page load, button click, mouse move, page scroll etc.

We will learn more about events in the next chapter. Lets see an example which uses the 'onclick' method to change the color of a paragraph.

Example: changing style when an event is fired

Run the code

Changing CSS property having hyphen

Javascript does not accept hyphen in variable name, function name or in property name, and suppose we want to add 'background-color', then what should we do?

Javascript accepts such property when provided in camelcase. Example 'background-color' => 'backgroundColor'

Property name in CSS To in Javascript
background-color => backgroundColor
background-image => backgroundImage
border-bottom => borderBottom
border-top => borderTop
box-shadow => boxShadow
font-size => fontSize
font-family => fontFamily
line-height => lineHeight
and so on...

Lets see some examples.

Example: changing backgroundColor using javascript

Run the code

Adding border property to the element

Example: adding border to element

Run the code

Creating Animation Using Javascript

Using Above javascript style properties we can create cool animation. With these only limits in creating animation is our imagination.

Let's create a simple animation of a moving ball.

Example: adding border to element

Run the code
DOM Manipulation