Chapter 41. Separating JavaScript and CSS

The HTML layer is arguably the most important because of its responsibility for getting data to the user, and the interaction between the HTML and JavaScript layers is important to the user's overall experience. JavaScript can interact with another layer, the CSS layer, which is responsible for how the page is displayed in the browser. Just as the HTML and JavaScript layers can be tightly integrated, the CSS and JavaScript layers can be coupled.

In Lesson 15, you learned how to change an element's style by using an element object's style property, like this:

var someEl = document.getElementById("someElement");

someEl.style.color = "red";
someEl.style.backgroundColor = "gray";
someEl.style.border = "1px solid black";

This code retrieves an element with an id of someElement and then changes various CSS properties to change how the element renders in the browser. The code works fine, but it suffers from problems like those of coupled HTML and JavaScript in that it makes maintenance more difficult. Not only do you have to revisit this code whenever you want to change the color, backgroundColor, and border properties, but making additional style changes requires an additional line of code for every property you want to change. Code such as this essentially makes JavaScript share the presentation role that is supposed to be the role of CSS.

Another issue is performance. To use the style object you access a DOM object — a poorly performing operation. ...

Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.