Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 5.6Styling with JavaScript

Part 5.6Styling with JavaScript

HTML is a markup language that describes a document. Documents can be completely static and have absolutely no interactive elements - but this is very rare these days. Documents tend to feature interactions and responses that make the document less dull.

One of the most important features of JavaScript is being able to manipulate the DOM. Changing the appearance of certain elements is very important to make a page interactive.

JavaScript style

CSS defines styling for a document. This is done with property and property value pairs. For example:

CSS
.coloured {
  color : green;
  background-color : orange;
}

With this class added to an element certain styles would be applied to any element. These styles are static and cannot be changed directly by CSS (unless using some pseudo selectors such as hover). JavaScript is required to change these styles.

The following Preview will be used for manipulation in the following examples.

An element

Changing the colours

The following sample will change the colours of the element.

JavaScript
var e = document.getElementById('sample_box');
e.style.backgroundColor = 'green';
e.style.color = 'orange';

Notice that in CSS the property name is background-color whereas in JavaScript is it is backgroundColor.

Changing the border-radius

Another style that is often changed is the border-radius CSS property. As before, since JavaScript uses camel casing, the CSS border-radius property becomes borderRadius

JavaScript
var e = document.getElementById('sample_box');
e.style.borderRadius = '5px';

Changing the width

It is also possible to change the width of an element. However, since the CSS width property is only one word in length, the JavaScript style property is the same:

JavaScript
var e = document.getElementById('sample_box');
e.style.width = '500px';

Changing the padding and margins

The following sample changes the CSS padding and margin properties:

JavaScript
var e = document.getElementById('sample_box');
e.style.padding = '10px';
e.style.margin = '20px';

Things to note

It's important to note that JavaScript styles are the same as CSS styles but they use different names for the properties. This is likely because of the way JavaScript's syntax was designed, since it prefers camel case syntax over dashed syntax (such as backgroundColor vs background-color)

The following is a list of all supported styles in this browser, generated by JavaScript.

Feedback 👍
Comments are sent via email to me.