I want to filter the type column, one button filters the aquatic and in the other all except the aquatic
JavaScript
x
40
40
1
<button type="button" onclick="Aquatic()">Aquatic</button>
2
<button type="button" onclick="NotAquatic()" >everything but aquatic</button>
3
<table class="table" >
4
<thead>
5
<tr>
6
<th scope="col">Animal</th>
7
<th scope="col">Type </th>
8
</tr>
9
</thead>
10
<tbody id="" >
11
<tr>
12
<td>bat</td>
13
<td>aerial</td>
14
</tr>
15
<tr>
16
<td>Fish</td>
17
<td>Aquatic</td>
18
</tr>
19
<tr>
20
<td>Horse</td>
21
<td>Land</td>
22
</tr>
23
<tr>
24
<td>Shark</td>
25
<td>Aquatic</td>
26
</tr>
27
<tr>
28
<td>Elephant</td>
29
<td>Land</td>
30
</tr>
31
<tr>
32
<td>Whale</td>
33
<td>Aquatic</td>
34
</tr>
35
<tr>
36
<td>dove</td>
37
<td>aerial</td>
38
</tr>
39
</tbody>
40
</table>
Advertisement
Answer
Hopefully this helps point you in the right direction! have a filterTable function which grabs all the table rows, and removes any inline style changes previously added to display. Then, I filter all the tr
s by the innerHTML content not including the term, and I take all those tr
s and set their display to none
JavaScript
1
16
16
1
function filterTable(aquaShown) {
2
const trs = [document.querySelectorAll("tbody tr")];
3
trs.forEach(tr => tr.style.display = "");
4
const hiddenTrs = aquaShown ?
5
trs.filter(tr => !tr.innerHTML.includes("Aquatic")) :
6
trs.filter(tr => tr.innerHTML.includes("Aquatic"));
7
hiddenTrs.forEach(tr => tr.style.display = "none");
8
}
9
10
function aquatic() {
11
filterTable(true);
12
}
13
14
function nonaquatic() {
15
filterTable(false);
16
}
JavaScript
1
32
32
1
<button type="button" onclick="aquatic()">Aquatic</button>
2
<button type="button" onclick="nonaquatic()">Non-Aquatic</button>
3
<table class="table">
4
<thead>
5
<tr>
6
<th scope="col">Animal</th>
7
<th scope="col">Type </th>
8
</tr>
9
</thead>
10
<tbody id="">
11
<tr>
12
<td>Fish</td>
13
<td>Aquatic</td>
14
</tr>
15
<tr>
16
<td>Horse</td>
17
<td>Land</td>
18
</tr>
19
<tr>
20
<td>Shark</td>
21
<td>Aquatic</td>
22
</tr>
23
<tr>
24
<td>Elephant</td>
25
<td>Land</td>
26
</tr>
27
<tr>
28
<td>Whale</td>
29
<td>Aquatic</td>
30
</tr>
31
</tbody>
32
</table>
EDIT refactored based on further clarification in comments