简体   繁体   中英

want to changing text color with JavaScript

<script>
function fun(){
    var a = document.getElementsByTagName("td");
    var a1 = a[0].innerHTML; 
    var a2 = a[1].innerHTML; 
    var a3 = a[2].innerHTML; 
    var a4 = a[3].innerHTML; 
    var a5 = a[4].innerHTML; 
    var b;
        if ( a1 == 55 ) { b = "red"; }
        else { b = "black"; }
            a[0].style.color = b;
}
</script>
<body onload="fun()" style="margin: 100px;">
    <table>
    <th>
        <td>55</td> 
        <td>34</td> 
        <td>25</td> 
        <td>55</td> 
        <td>25</td> 
     </th>
    </table>
</body>

I want all 55 amount under <td> in red. My table is big so I want shortcuts. I trying JavaScript loop, but not worked well, some get errors.

You need to use iterator

var a = document.getElementsByTagName("td");
for (var i = 0; i < a.length; i++) {
   if(a[i].innerHTML === "55") {
      a[i].style.color = "red";
   } else {
      a[i].style.color = "black";
   }
}

For reference - http://plnkr.co/edit/fJdVCvv4Ax7NwkJiTZRV?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM