简体   繁体   中英

hide all elements with ID

I am wanting to hide all elements with the id=showhide

So I set my javascript as

<script type="text/javascript">

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
</script>
</body>

and then my button as

<a href="#" onclick="toggle_visibility('showhide');">
                            <button>Show / Hide Details</button>
                            </a>

then I went and added the ID to a table, but it's only hiding the first instance of this ID, not all?

Like others have mentioned, you need to use a class instead of id. getElementById returns only one element while getElementsByClassName will return a collection of all elements (NodeList ) with that class. I've attached a snippet showcasing how the code could look.

 function toggle_visibility(className) { const elements = document.getElementsByClassName(className); for (const e of elements) { e.style.display = e.style.display === 'none' ? 'block' : 'none'; } }
 <button onclick="toggle_visibility('showhide');"> Show / Hide Details </button> <div class="showhide">A</div> <div class="showhide">B</div> <div class="showhide">C</div>

You can not use id for this purposes. ID by it's ideology must be the SINGLUAR in your html. You can for instance use classes and document.getElementsByClassName Or you can use some specific attributes, whatever more convinient for you except ID's.

well a better way to do this is to use getElementsByClassName() :

function toggle_visibility(class) {
var elements = getElementsByClassName("showhide");
for (e of elements) {
    if (elements[e].style.display == "block") {
          elements[e].style.display = "none";
    }else {
          element[e].style.display = "block";
    }
}
}

and add that class to the rows or anything u want the button to toggle visibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM