简体   繁体   中英

hide table rows in JavaScript based on value of first cell

I have an HTML table i need to filter. I don't know why it won't work. I've tried to put the i in '' but it did't worked. I think the error is with the for loop, or in the querySelector.


function filtern(){
var reih = document.querySelector('.mon_list').rows.length
for (var i= 2: i <= reih; i++;){
if ((document.querySelector('.mon_list tr:nth-Child(i) td:nth-Child(1)').innerHTML) != ("5a")){
document.querySelector('.mon_list tr:nth-Child(i)').style.display='none';
}
}
document.getElementById("demo2").innerHTML = document.querySelector('.mon_list tr:nth-Child(2) td:nth-Child(1)').innerHTML;
document.getElementById('demo').innerHTML = reih;
}
filtern();

and the HTML

<head>
</head>
<body>
<p>
<table class="mon_list" >
<tr class='list'><th class="list" align="center"><b>Klasse(n)</b></th>
<th class="list" align="center">Stunde</th>
<th class="list" align="center">(Lehrer)</th>
<th class="list" align="center"><b>Vertreter</b>
</th><th class="list" align="center">Fach</th>
<th class="list" align="center">Raum</th><th class="list" align="center">Vertretungs-Text</th>
</tr>
<tr class='list odd'><td class="list" align="center">
<b>5a</b></td><td class="list" align="center">5</td>
<td class="list" align="center">Se</td>
<td class="list" align="center"><b>Ma</b>
</td><td class="list" align="center">BNT-b</td>
<td class="list" align="center">2.25</td>
<td class="list" align="center">Vertretung</td>
</tr>
<tr class='list even'><td class="list" align="center"><b>5a</b></td>
<td class="list" align="center">6</td>
<td class="list" align="center">Se</td>
<td class="list" align="center"><b>---</b></td>
<td class="list" align="center">---</td>
<td class="list" align="center">---</td>
<td class="list" align="center">frei</td>
</tr>
</table>
</p>
<p id="demo"></p>
<p id="demo2"></p>
</body>

Change your if condition and inner statements notice the concatenation of variable ' + i + ' . You have used it as string it should be number.

if ((document.querySelector('.mon_list tr:nth-Child(' + i + ') td:nth-Child(1)').innerHTML) != ("5a")){
      document.querySelector('.mon_list tr:nth-Child(' + i + ')').style.display='none';
}

also in for loop use semicolon(;) instead of colon(:) and remove semicolon after i++

for (var i = 2; i <= reih; i++) {

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