Javascript is well-known for its ability to change the structure of web pages, inserting or deleting HTML elements at will. The Javascript standard allows for more modifications to web pages through visual styling of elements as well.

Modifying CSS through Javascript does not impact the Document Object Model (DOM) since it deals with stylistic modifications on existing web page elements. Any HTML element is targetable through Javascript CSS.

This article discusses how to modify HTML element styling with Javascript CSS, followed by the potential benefits and drawbacks of Javascript CSS compared to external CSS files. Finally, this article provides guidelines for choosing when to use Javascript CSS.

Javascript CSS with the Element Style Property

Every HTML element in the Javascript DOM contains a Javascript object property called style. The style object contains many properties that correspond to CSS properties, so you can set properties on the style object to change element CSS styles directly.

The style object property names are consistent with basic CSS properties. For example, the Javascript CSS property to set an element’s foreground color is exactly the same as its usual CSS property:

color: black;                       // CSS
document.body.style.color = "black" // Javascript CSS

All CSS properties are accessible directly through the style object; there is no need to wade through sub-objects to find the CSS property you want to change. Since there are no sub-objects some CSS property names get a little long in Javascript, like backgroundColor, but the simplicity of accessing everything directly from the style object usually outweighs the occasional cumbersome property length.

In the following example, the backgroundColor property in the first line is used in camel case as a property of the style object. The second line attempts to create a background color property incorrectly, with color as a sub-property of the style property “background”. There is no camel case in the second line, but developers would be required to remember a complex property hierarchy if Javascript CSS specified all properties this way.

document.body.style.backgroundColor = "black";   // correct
document.body.style.background.color = "black";  // wrong

Since the Javascript standard and the CSS standard are managed by different organizations, there is always some lag between the most recent additions to the CSS standard and the ability to change those properties with Javascript CSS. The lag has lessened in recent years because the Javascript standard is now updated yearly.

Javascript CSS Versus External CSS

Javascript CSS looks slightly different from external CSS because Javascript has different linguistic conventions than pure CSS. Many properties in external CSS files include hyphens in their names, and Javascript does not allow hyphens in its property names.

Javascript CSS removes hyphens from CSS property names and identifies words using camel case. Using camel case means that CSS properties which are only a single word look identical in external CSS files compared to Javascript CSS, while those properties with multiple words look different.

// The "margin" property in external CSS and Javascript CSS.
margin: 0px;
document.body.style.margin = "0px";

// The "background color" property in external CSS and Javascript CSS.
background-color: white;
document.body.style.backgroundColor = "white";

Changing Javascript CSS with Events

Changes to Javascript CSS do not happen on their own; they happen in response to the user interacting with a web page. Every interaction a user makes with a web page is called an “event,” and Javascript reacts to these events with structures called event listeners.

A common place to find Javascript CSS is in an event listener that activates when a button is clicked, opening a collapsed section of a web page. In this example, an event listener is added to a button, and the listener checks the display status of the HTML element with ID “myDiv” when the button is clicked. If the “myDiv” element is hidden, it’s set to display after a button click, and vice versa.

let button = document.createElement('button');

button.addEventListener('click', event => {
    let myDiv = document.getElementById("myDiv");
    if (myDiv.style.display === "none") {
        document.getElementById("myDiv").style.display = "block";
    } else {
        document.getElementById("myDiv").style.display = "none";
    }
});

Choosing to Use Javascript CSS

When choosing whether to use Javascript CSS, maintenance is a major concern. It can be more difficult to maintain Javascript CSS than to maintain external CSS files because you need to know Javascript and CSS simultaneously. Unless you are certain that anyone who reads your code will understand Javascript and CSS, it may be best to keep your Javascript and CSS separate from each other.

Since Javascript is not always up-to-date with the newest CSS features, it is best to use external CSS when relying on the newest CSS. Well-established CSS properties are reliable in Javascript, but anything bleeding-edge won’t be available in the Javascript standard immediately.

Conclusion

Javascript CSS uses the style property to modify HTML element styles. Although it functions in essentially the same way as external CSS files, Javascript CSS requires slightly different syntax. These syntax differences can be confusing for careless developers.

Setting CSS properties through Javascript is technically a violation of the traditional programming axiom that the styling portion of a project should be kept separate from its structure and scripts. CSS deals with visual styling, so incorporating it into Javascript code muddles these boundaries.

Many developers find it harder to maintain Javascript CSS compared to external CSS files. Use Javascript CSS with care, and take steps to make sure it is clear for future developers.

Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript CSS and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni