O'Reilly logo

JavaScript® 24-Hour Trainer by Jeremy McPeak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required