Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapsing and Expanding lists in javascript

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>
like image 335
stefan Avatar asked Nov 30 '25 18:11

stefan


1 Answers

You could use the class attribute for that.

<li>
 <a href="#" onclick="test('node1')">hello</a>
 <ul id="node1" class="node" 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="node2" class="node" style="display:none">
  <li>Sub-item 1</li>
  <li>Sub-item 2</li>
 </ul>
</li>

Assuming that you really want to collapse all of them and not toggle their visibility you could write something like this...

function test2(className, link) {
 var e = document.getElementsByClassName(className);

 for (var i = 0, len = e.length; i < len; i++) {
  e[i].style.display = "none";
 }

 link.innerHTML = "Expand";
}

...and call it like that...

<a href="#" onclick="test2('node', this)">Collapse</a>

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:

#mutualParent.hide-nodes li.node {
 display: none;
}

Then change your function like this...

function test2(className) {
 document.getElementById("mutualParent").className += className;
}

...and call it like that:

<a href="#" onclick="test2('hide-nodes')">Collapse</a>

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.

like image 183
greiner Avatar answered Dec 03 '25 08:12

greiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!