Web programming lesson time: if you want to set styles, don't use JavaScript to set the style, use CSS for the styling definitions, and then only use JavaScript to point to that CSS.
In your CSS:
.highlight {
color: pink;
background: blue;
font-style: fantasy;
whatever-else: StuffGoesHere;
}
And then your button handling:
button.addEventListener("click", function(evt) {
var e = find.your.element.however.you.need();
e.classList.toggle("highlight");
});
Magic: simply by doing things the right way, the code is extremely straight forward, AND we're not hardcoding the styling, we're simply referring to where styling should be defined.
"But what if the browser doesn't support .classList?": the only reason to say this is because you did not keep up with how much browser have improved. Every browser supports classList
.
Of course, if you need to do more than just toggles, write your function as a standalone operation, and throw elements at it:
var records = {};
function toggleHighlight(e) {
e.classList.toggle("highlight");
if (e.classList.contains("highlight")) {
// element is now highlighted, do things accordingly:
records[e.id] = e.textContent;
// ...
} else {
records[e.id] = false;
// ...
}
}
button.addEventListener("click", function(evt) {
var e = find.your.element.however.you.need();
toggleHighlight(e);
});