I’m using a tutorial to make collapsible lists in HTML.
My HTML looks like this:
<li>
<a href="#" onclick="test('node1')">hello</a>
<ul id="node3" style="display:none">
<li>Sub-item 1</li>
<li>Sub-item 2</li>
</ul>
</li>
<li>
<a href="#" onclick="test('node2')">test</a>
<ul id="node3" style="display:none">
<li>Sub-item 1</li>
<li>Sub-item 2</li>
</ul>
</li>
node 3,4,5,etc
I’m trying to collapse all these tables using the following JavaScript:
function test2(id, link) {
var e = document.getElementById(id);
if (e.style.display == '') {
e.style.display = 'none';
link.innerHTML = 'Expand';
} else {
e.style.display = '';
link.innerHTML = 'Collapse';
}
}
But when I call the function I’m not too sure what to enter to select all nodes. I still need the individual control on each node, so I can’t change all the names to be the same.
<a href="#" onclick="test2('node????', this)">Collapse</a>
You could use the class attribute for that.
Assuming that you really want to collapse all of them and not toggle their visibility you could write something like this…
…and call it like that…
Keep in mind that getElementsByClassName does not work in older browsers (< IE9).
UPDATE:
An alternative way of achieving this is by using CSS and changing the class-name of a mutual parent element. Here’s a sample CSS code for that:
Then change your function like this…
…and call it like that:
If you want to toggle the visibility using the test()-function you need to remove the className first or otherwise it stays hidden. Also for this code to work you need to remove the style-attribute from the
<ul>tags because style attributes have a higher priority.