1unction filterTable() {
2 // Variables
3 let dropdown, table, rows, cells, country, filter;
4 dropdown = document.getElementById("countriesDropdown");
5 table = document.getElementById("myTable");
6 rows = table.getElementsByTagName("tr");
7 filter = dropdown.value;
8
9 // Loops through rows and hides those with countries that don't match the filter
10 for (let row of rows) { // `for...of` loops through the NodeList
11 cells = row.getElementsByTagName("td");
12 country = cells[1] || null; // gets the 2nd `td` or nothing
13 // if the filter is set to 'All', or this is the header row, or 2nd `td` text matches filter
14 if (filter === "All" || !country || (filter === country.textContent)) {
15 row.style.display = ""; // shows this row
16 }
17 else {
18 row.style.display = "none"; // hides this row
19 }
20 }
21}
22<select id="countriesDropdown" oninput="filterTable()">
23 <option>All</option>
24 <option>Sweden</option>
25 <option>Germany</option>
26</select>
27
28<table id="myTable">
29 <tr><th>Name</th><th>Country</th></tr><!-- header row uses 'th' instead of 'td' -->
30 <tr><td>Inga</td><td>Sweden</td></tr>
31 <tr><td>Helena</td><td>Sweden</td></tr>
32 <tr><td>Hans</td><td>Germany</td></tr>
33 <tr><td>Anna</td><td>Germany</td></tr>
34</table>