O'Reilly logo

DOM Enlightenment by Cody Lindley

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 9. CSS Stylesheets and CSS Rules

9.1 CSS Stylesheet Overview

A stylesheet is added to an HTML document by using either the HTMLLinkElement node (i.e., <link href="stylesheet.css" rel="stylesheet" type="text/css">) to include an external stylesheet or the HTMLStyleElement node (i.e., <style></style>) to define a stylesheet inline. In the following HTML document, both of these Element nodes are in the DOM and I verify which constructor constructs these nodes.

Live code

<!DOCTYPE html>
<html lang="en">
<head>

<link id="linkElement" 
  href="http://yui.yahooapis.com/3.3.0/build/cssreset/reset-min.css" 
  rel="stylesheet" type="text/css">

<style id="styleElement">
body{background-color:#fff;}
</style>

</head>
<body>

<script>

//logs function HTMLLinkElement() { [native code] }
console.log(document.querySelector('#linkElement').constructor);

//logs function HTMLStyleElement() { [native code] }
console.log(document.querySelector('#styleElement').constructor);

</script>
</body>
</html>

Once a stylesheet is added to an HTML document, it’s represented by the CSSStylesheet object. Each CSS rule (e.g., body{background-color:red;}) inside a stylesheet is represented by a CSSStyleRule object. In the following code, I verify which constructor constructed the stylesheet and each CSS rule (selector and its CSS properties and values) in the stylesheet.

Live code

<!DOCTYPE html>
<html lang="en">
<head>

<style id="styleElement">
body{background-color:#fff;}
</style>

</head>
<body>

<script>

/* logs function ...

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