className and classList
Changing a class is one of the most often used actions in scripts.
In the ancient time, there was a limitation in JavaScript: a reserved word like "class" could not be an object property. That limitation does not exist now, but at that time it was impossible to have a "class" property, like elem.class.
So for classes the similar-looking property "className" was introduced: the elem.className corresponds to the "class" attribute.
For instance:
<body class="main page"><script>alert(document.body.className); // main page</script></body>
If we assign something to elem.className, it replaces the whole string of classes. Sometimes that’s what we need, but often we want to add/remove a single class.
There’s another property for that: elem.classList.
The elem.classList is a special object with methods to add/remove/toggle a single class.
Methods of classList:
elem.classList.add/remove("class")– adds/removes the class.elem.classList.toggle("class")– adds the class if it doesn’t exist, otherwise removes it.elem.classList.contains("class")– checks for the given class, returnstrue/false.
Computed styles: getComputedStyle
So, modifying a style is easy. But how to read it?
For instance, we want to know the size, margins, the color of an element. How to do it?
The style property operates only on the value of the "style" attribute, without any CSS cascade.
So we can’t read anything that comes from CSS classes using elem.style.
For instance, here style doesn’t see the margin:
<head><style> body { color: red; margin: 5px } </style></head><body>The red text<script>alert(document.body.style.color); // emptyalert(document.body.style.marginTop); // empty</script></body>
…But what if we need, say, to increase the margin by 20px? We would want the current value of it.
There’s another method for that: getComputedStyle.
The syntax is:
getComputedStyle(element, [pseudo])
elementElement to read the value for.pseudoA pseudo-element if required, for instance ::before. An empty string or no argument means the element itself.
The result is an object with styles, like elem.style, but now with respect to all CSS classes.
