Search code examples
javascripttoggleshow-hide

Change button inner text on click in a function that hides/shows all elements with class


Found a way to show/hide all elements with class, but I need to change the button text on click from Hide to Show, than back again from Show to Hide. This is my JS code so far:

document.getElementById("hide").onclick = function() {
    var o = document.getElementsByClassName("details");
    for ( var i = 0; i < o.length; i++ ) {
        if (o[i].style.display == 'none') {
            o[i].style.display = 'block';
        } else {
            o[i].style.display = 'none';
        }
    }
}

Works as expected, so it hides and shows the elements with class, but I am not able to add the inner text change for the button. This is my html:

<button id="hide">Hide</button>
<ul>
    <li>
        <h3>First Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
    <li>
        <h3>Second Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
    <li>
        <h3>Third Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
</ul>

Solution

  • Updated your code, run the script below.

    I took your button and targeted the innerHTML. More info here.

    document.getElementById("hide").onclick = function() {
        var o = document.getElementsByClassName("details");
        var btn = document.getElementById("hide");
        for ( var i = 0; i < o.length; i++ ) {
            if (o[i].style.display == 'none') {
                o[i].style.display = 'block';
                btn.innerHTML = "Hide";
            } else {
                o[i].style.display = 'none';
                btn.innerHTML = "Show";
            }
        }
    }
    <button id="hide">Hide</button>
    <ul>
        <li>
            <h3>First Item</h3>
            <ul class="details">
                <li>Detail 1</li>
                <li>Detail 2</li>
                <li>Detail 3</li>
            </ul>
        </li>
        <li>
            <h3>Second Item</h3>
            <ul class="details">
                <li>Detail 1</li>
                <li>Detail 2</li>
                <li>Detail 3</li>
            </ul>
        </li>
        <li>
            <h3>Third Item</h3>
            <ul class="details">
                <li>Detail 1</li>
                <li>Detail 2</li>
                <li>Detail 3</li>
            </ul>
        </li>
    </ul>