In this blog post, we will learn how to alternate colors in JavaScript. This can be useful for various purposes like styling tables, lists, or any other elements that require alternating colors to improve readability.
Alternating Colors using JavaScript and CSS classes
The best way to alternate colors in JavaScript is by using CSS classes. First, let’s create two CSS classes for our alternating colors:
.even {
background-color: #f1f1f1;
}
.odd {
background-color: #ffffff;
}
Now, let’s use JavaScript to add these classes to our elements. In the example below, we will alternate the background colors of table rows:
<table id="myTable">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
<tr><td>Row 4</td></tr>
</table>
Next, add the following JavaScript code to alternate the colors of the table rows:
const table = document.getElementById("myTable");
const rows = table.getElementsByTagName("tr");
for (let i = 0; i < rows.length; i++) {
if (i % 2 === 0) {
rows[i].classList.add("even");
} else {
rows[i].classList.add("odd");
}
}
With this code, we are looping through all the rows in the table and adding the even
class to even rows and the odd
class to odd rows.
Alternating Colors using JavaScript and Inline Styles
While using CSS classes is recommended, you can also alternate colors by directly applying inline styles using JavaScript. Here’s an example of how to do this:
const table = document.getElementById("myTable");
const rows = table.getElementsByTagName("tr");
for (let i = 0; i < rows.length; i++) {
if (i % 2 === 0) {
rows[i].style.backgroundColor = "#f1f1f1";
} else {
rows[i].style.backgroundColor = "#ffffff";
}
}
This code snippet does the same thing as the previous one but instead of adding CSS classes, it directly sets the backgroundColor
property of the table rows.
Conclusion
Alternating colors in JavaScript can be easily achieved by using CSS classes or inline styles. Using CSS classes is the recommended approach as it separates presentation logic (CSS) from behavior logic (JavaScript), making the code more maintainable and easier to understand.