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:
.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.
Changing the colours
The following sample will change the colours of the element.
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
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:
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:
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.