Edit Node Styles

The style attribute of HTML elements lets us define in-line styles of an element. In-line style has the highest specificity in the cascading rule. Which means they take precedence over styles defined in style sheets or under a <style> element. We can dynamically change the in-line style values through the style property of HTMLElements. Calling the Element.style property will return an object typed CSSStyleDeclaration representing the entire in-line style settings for an element. The style property also has a property called cssText which will return a String of the actual value of the style attribute.

<p style="color: blue;">
  Hello World!
</p>
var styleObject = document.getElementsByTagName('p')[0].style;
console.log(styleObject);
// -> CSSStyleDeclaration {
// ->   0: 'color',
// ->   alignContent: '',
// ->   alignItems: '',
// ->   alignSelf: '',
// ->   alignmentBaseline: '',
// ->   all: '',
// ->   animation: '',
// ->   ...
// -> }

console.log(styleObject.cssText);
// -> color: blue;

Changing In-line Style

There are three ways you can change the style value of an element. Two of them will completely overwrite the entire style property, which is not recommend unless that is exactly what you want to do. The third method lets you edit one CSS property at a time.

To set multiple CSS properties in one go, you can either assign a new string value to the style.cssText property, or use Element.setAttribute on the style attribute.

// These two methods will overwrite entire style value, recommended only for setting multiple CSS properties at one.
var p = document.getElementsByTagName('p')[0];
p.style.cssText = 'color: red; font-size: 20px;';

p.setAttribute('style', 'color: green; font-size: 12px;');

If you just want to edit one CSS property without wiping other existing in-line style definitions, you can do so by accessing the exact CSS property from the style object. Notice CSS property names in the style object are in camel-case fontSize rather than kebab-case font-size. Because - is not an acceptable character for variables in JavaScript and cannot be used in dot notation when accessing object properties. To clear a CSS property, just assign an empty sting value to the property

Lets have a little fun here by creating a function that will generate a random RGB color and set it as the background color of the document body.

var randomBackground = function () {
  var rgb = [0, 0, 0].map(function () {
    return Math.floor(Math.random() * 256);
  });

  document.body.style.backgroundColor = 'rgb(' + rgb.join(',') + ')';
};

var clearBackground = function () {
  document.body.style.backgroundColor = '';
}

Try it on Repl.

I also included a disco mode in the example, which uses the in-built setInterval function of JavaScript. It lets you repeat a certain program every so many milliseconds, I won't go through timers here since it will be covered in a later chapter. But you can have a sneak peek at how it works in the example, if you dare.

Info: For a list of common CSS properties, see MDN.

Style Elements

Recall that we can add CSS rules in a <style> element directly in a HTML file. We can replicate this using JavaScript as well. Say we want to mimic the following HTML document.

<head>
  <style>
    #paragraph1 {
      color: red;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <p id="paragraph1">
    red and bold.
  </p>
</body>

We just need to create a style element node, inject the CSS rule as innerHTML and append the new node to the <head> element.

var addCSSNode = function () {
  var styleNode = document.createElement('style');
  styleNode.innerHTML = '#paragraph1 {color: red; font-weight: bold;}';

  document.getElementsByTagName('head')[0].appendChild(styleNode);
};

Try it on Repl.

Style Sheets

Note: A slightly more advanced topic here. If you find it hard to understand, you can move on to the next chapter. Knowledge in this part is seldom used unless you are working on very advanced projects.

Apart from using style elements to add CSS rules to your HTML, you can also use separate style sheet files to write your CSS. When the browser sees a link to a style sheet file, it will process the file and add it to the document.styleSheets property. Embedded <style> elements are also considered as style sheets, they too get added to the document.styleSheets property.

The document.styleSheets is an array like StyleSheetList that contains all the style sheets linked to and embedded in a HTML file. We can access each style sheet using bracket notation. Each style sheet is represented as a CSSStyleSheet object.

In our example page, we have one style sheet file called index.css, the embedded style element in the above section won't appear in the styleSheets object unless we run the addCSSNode function.

console.log(document.styleSheets.length);
// -> 1

addCSSNode();
console.log(document.styleSheets.length);
// -> 2

The first style sheet should be the external style sheet file. We can check it by printing the href value of the CSSStyleSheet object.

console.log(document.styleSheets[0].href);
// -> /index.css

The most interesting part of a CSSStyleSheet object is its cssRules property. It contains all the CSS rules defined in a style sheet. It is a live array like CSSRuleList. Each rule value is an object of the interface CSSRule. There are many variations of CSSRule, standard CSS style rules are represented as a CSSStyleRule object. A CSSStyleRule object contains a selectorText property and a style property.

selectorText is a string representation of the CSS rule's selector, i.e. 'p', '.red-text', 'div > ul > li > a'.

style is a an object containing the CSS properties defined in this rule. One of those properties is cssText which stores all the property declarations defined in this particular rule. Our index.css style sheet doesn't have any rules defined, so lets add a couple rules and then access than via JavaScript.

p {
  color: yellow;
}
button {
  background-color: yellow;
}
var rules = document.styleSheets[0].cssRules;
for (var i = 0; i < rules.length; i++) {
  console.log(rules[i].selectorText + ' { ' + rules[i].style.cssText + ' }');
}
// -> p { color: yellow; }
// -> button { background-color: yellow; }

we can edit a particular CSS property in a CSS rule by assigning a new value to a CSS property.

for (var i = 0; i < rules.length; i++) {
  if (rules[i].selectorText === 'button') {
    rules[i].style.backgroundColor = 'green';
  }
}

If a rule doesn't exist, we can always add it in using the CSSStyleSheet.insertRule property. It accepts two arguments. The string representation of the CSS rule, and an integer for the index position you want to insert into the cssRules list.

document.styleSheets[0].insertRule('body { background-color: lime; }');

You can also remove a rule using CSSStyleSheet.deleteRule method.

document.styleSheets[0].deleteRule(2);

Try it on Repl.

The above removes the CSS rule on button elements.

results matching ""

    No results matching ""