CSSOM

An Introduction and Guide to the CSS Object Model (CSSOM)

If you've been writing JavaScript for some time now, it's almost certain you've written some scripts dealing with the Document Object Model (DOM). DOM scripting takes advantage of the fact that a web page opens up a set of APIs (or interfaces) so you can manipulate and otherwise deal with elements on a page.

But there's another object model you might want to become more familiar with: The CSS Object Model (CSSOM). Likely you've already used it but didn't necessarily realize it.

In this guide, I'm going to go through many of the most important features of the CSSOM, starting with stuff that's more commonly known, then moving on to some more obscure, but practical, features.

(more…)

Working With the new CSS Typed Object Model

Eric Bidelman introduces the CSS Typed Object Model. It looks like it's going to make dealing with getting and setting style values through JavaScript easier and less error-prone. Less stringy, more number-y when appropriate.

Like if we wanted to know the padding of an element, classically we'd do:

var el = document.querySelector("#thing");
var style = window.getComputedStyle(el);
console.log(style.padding);

And we'd get "20px" as a string or whatever it is.

One of these new API's lets us pull it off like this:

console.log(
  el.computedStyleMap().get('padding').value,
  el.computedStyleMap().get('padding').unit
);

And we get 20 as a real number and "px" as a string.

There is also attributeStyleMap with getters and setters, as well as functions for each of the values (e.g. CSS.px() CSS.vw()).

Eric counts the benefits:

  1. Few bugs.
  2. Arithmetic operations & unit conversion.
  3. Value clamping & rounding.
  4. Better performance.
  5. Error handling.
  6. Naming matches CSS exactly.
icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag