I am currently working on an HTML document that contains a table. The table structure is as follows:
<table>
<tr>
<th class="street">Street</th>
<th class="city">City</th>
<th class="country">Country</th>
</tr>
<tr>
<td class="street">street-1</td>
<td class="city">city-1</td>
<td class="country">country-1</td>
</tr>
<tr>
<td class="street">street-2</td>
<td class="city">city-2</td>
<td class="country">country-2</td>
</tr>
</table>
My goal now is to implement buttons in the document, such as:
<button id="button_street">TOGGLE STREET</button>
<button id="button_city">TOGGLE CITY</button>
<button id="button_country">TOGGLE COUNTRY</button>
When a button is clicked, I want the corresponding column in the table to be either hidden or have its css design changed.
Currently, my solution involves using a somewhat cumbersome javascript method that toggles classes:
Spry.Utils.addLoadListener(function() {
let buttonToggle = document.getElementById('button_street');
buttonToggle.addEventListener('click', toggleClass);
function toggleClass() {
let collection = document.getElementsByClassName("street");
for (var i=0; i<collection.length; i++) {
collection[i].classList.toggle('street_design2');
}
}
}
This approach needs to be repeated for each button, but I'm wondering if there is a more efficient way to achieve this functionality across all elements with the same class.
In addition, I am exploring the possibility of passing functions to an array instead of repeating them individually for each button. Is there a more streamlined solution involving loops?
The relevant css styles are defined as follows:
.street {
background-color: blue;
}
.street_design2 {
background-color: red;
}
If I wish to hide the "street" column entirely, I can use display: none
.
- So far, I haven't come across a javascript solution that addresses all instances of a specific class like "street". Is there a better alternative available?
- Moreover, I am interested in consolidating and optimizing the implementation by utilizing arrays and loops. Any insights into achieving this?