settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Colorize Table Task in HTML with DOM and JavaScript

+3 votes

Write a JS function that changes the color of all even rows when the user clicks a button. Apply the color "Teal" to the target rows.

Input/Output:
There will be no input/output, your program should instead modify the DOM of the given HTML document.

Sample HTML:

<table>
  <tr><th>Name</th><th>Town</th></tr>
  <tr><td>Eve</td><td>Sofia</td></tr>
  <tr><td>Nick</td><td>Varna</td></tr>
  <tr><td>Didi</td><td>Ruse</td></tr>
  <tr><td>Tedy</td><td>Varna</td></tr>
</table>
<button onclick="colorize()">Colorize</button>
<script>
  function colorize() {
    // TODO
  }
</script>

Examples:

colorize table with html, dom and javascript

asked in JavaScript category by user hues

2 Answers

+2 votes

Here is my solution:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<table border="1">
    <tr>
        <th>Name</th>
        <th>Town</th>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Sofia</td>
    </tr>
    <tr>
        <td>Nick</td>
        <td>Varna</td>
    </tr>
    <tr>
        <td>Didi</td>
        <td>Ruse</td>
    </tr>
    <tr>
        <td>Tedy</td>
        <td>Varna</td>
    </tr>
</table>
<br>
<button onclick="colorize()">Colorize The Rows</button>

<script>
    function colorize() {
        let i = 0;
        let teal = document.querySelectorAll("table tr");
        for (let tr of teal) {
            if (i % 2 != 0) {
                tr.style.background = "teal";
            }
            i++
        }
    }
    //    or
    //    function colorize() {
    //        let rows = document.querySelectorAll("table tr");
    //        for (let i = 0; i < rows.length; i++) {
    //            if (i % 2 != 0) {
    //                rows[i].style.background = "teal";
    //            }
    //        }
    //    }
</script>
</body>
</html>

 

answered by user icabe
0 votes

Another solution with the  function colorize():

function colorize() {
    let rows = document.querySelectorAll("table tr");
    for (let i = 0; i < rows.length; i++) {
        if (i % 2 != 0) {
            rows[i].style.background = "teal";
        }
    }
}

 

answered by user john7
...