I have a question that I can't seem to find the answer to. Despite numerous Google searches showing jquery solutions, I'd rather stick with vanilla JavaScript as I'm new to it and want to master it before moving on to libraries. My goal is to have a button collapse part of a table when clicked and then show those hidden parts again on a second click, essentially toggling the display of a specific element class.
When I click the button that calls the test()
function, nothing seems to happen to my table. Here's the JavaScript code I'm using. I rely on collapse[0]
because as far as I know, collapse
is a nodeList and I always manipulate all elements together so checking the first one should be enough.
function test() {
var collapse = document.getElementsByClassName("catOne");
var i = 0; // Loop counter
if (collapse[0].style.display === "table-row") {
for (i = 0; i < collapse.length; i += 1) {
collapse[i].style.display = "none";
}
}
if (collapse[0].style.display === "none") {
for (i = 0; i < collapse.length; i += 1) {
collapse[i].style.display = "table-row";
}
}
}
I've tested this function with the following code:
function test() {
var collapse = document.getElementsByClassName("catOne");
var i = 0; // Loop counter
for (i = 0; i < collapse.length; i += 1) {
collapse[i].style.display = "none";
}
This works fine in collapsing the elements, meaning the issue likely lies within my if statement. However, my IDE, Netbeans, isn't flagging any errors, so it should be functioning correctly based on what I can see.
Thank you for any assistance provided.
Link to HTML and JavaScript: https://jsfiddle.net/ozjbekjy/