if statements and for loops in css
An novel take on CSS selectors as if statements and for loops:
menu a {
color:red;
}
menu a:first-child {
color: blue;
}
menu a:not(#current) {
color: red;
}
Now do that imperatively in JS:
for (all menus) {
for (all links in this menu) {
let first = [figure out if this is the first link in the menu]
if (first) {
link.color = 'blue'
} else if (link.id !== 'current') {
link.color = 'red';
}
}
}
The drawback of the JavaScript version is that it’s more verbose than the CSS version, and hence more prone to error. The advantage is that it offers much finer control than CSS. In CSS, we’ve just about reached the limits of what we can express. We could add a lot more logic to the JavaScript version, if we wish.
In CSS, we tell the browser how links should look. In JavaScript, we describe the algorithm for figuring out how an individual link should look.