Colorize DOM elements
Last updated:
Introduction
Lets say we opened a webpage that displays collections of data items that contains DOM elements with numerical values (e.g. posts with view counts, ratings…) and we want to colorize them so we can visually scan for patterns or outliers.
To solve this we will bump into a few pitfalls specific to Javascript when handling different “array-like” structures.
The approach described here can be simply run from the browser’s dev console on any webpage we want to process.
Selecting the DOM elements
We will use document.querySelectorAll()
to select the elements we want, it returns a nodes object, which can be traversed by forEach()
.
It is not an array so it will not support map()
, if we still want to it for a more functional approach we will first need to case it
into an array type first using Array.from()
. (The increase in memory used should not have a noticeable impact for this use case.)
Math.max()
, which we’ll use to determine the maximum value, also doesn’t work with arrays, instead we need to pass all the values as parameters.
This means we will need to use the spread operator (...
).
We’ll assume that the innerText
of an element will contain text containing a single integer, e.g. “42 points”, this means we can simply use parseInt()
to get the number.
Thus to get the max value from the selected elements we can use the following code:
const maxValue = Math.max( ...Array.from(list).map( (item) => parseInt(item.innerText, 10) ));
Adding some color
Once we have the elements we want to color we can iterate through them to apply the new values using forEach()
:
const list = document.querySelectorAll('.score');const maxValue = Math.max(...Array.from(list).map((item) => parseInt(item.innerText, 10)));
list.forEach((item) => { hexValue = (Math.floor(parseInt(item.innerText, 10)/320*256)).toString(16); if (hexValue.length === 1) { hexValue = '0'+hexValue}; color = `#00${hexValue}00`; item.style.color = color;})
If needed the color mapping can be extended to render more values.