简体   繁体   中英

Hide DIVs with the same name using Javascript

I want to hide all divs with the name "mask"

This is my HTML :

<div id="first">
 <div id="firsttest"></div>
  <div class="one onehelp">
   <div id="mask">
    <div id="onetip"></div>
   </div>
   <div id="Div5"></div>
   <div id="resultone"></div>
  </div>
  <div class="two twohelp">
   <div id="mask">
    <div id="twotip"></div>
   </div>
   <div id="Div6"></div>
   <div id="resulttwo"></div>
  </div>
  <div class="three threehelp">
   <div id="mask">
    <div id="threetip"></div>
   </div>
   <div id="Div7"></div>
   <div id="resultthree"></div>
  </div>
</div>

I tried to hide "mask" by using the JS code below but it didn't work for all divs, just for the first one.

var hidemask = document.getElementById("mask");
hidemask.style.display = "none";

Is there a way to hide them all by using pure Javascript. No jQuery.

You shouldn't be using duplicate ID's in HTML, consider changing it to a class.

If you change id="mask" to class="mask" , then you can do:

var hidemask = document.querySelectorAll(".mask");

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

Or for browsers still in the stone age (IE7 and below), you can do:

    var elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if((' ' + elems[i].className + ' ').indexOf(' ' + 'mask' + ' ') > -1) {
            elems[i].style.display = "none";
        }
    }

The id attribute must be unique per document. You can do what you want with a class , perhaps. So you would have multiple div s like so:

<div id="something" class="mask"></div>

Then you can do:

var divsWithMask = document.querySelectorAll(".mask");
for(var i = 0; i < divsWithMark.length; i++) {
    divsWithMak[i].style.display = "none";
}

You cannot assign same ID more than once.

But you can add an attribute class to div with id "mask" Eg:

<div id="mask-or-something-else" class="mask">...</div>

And select all elements by this class:

var hidemask = document.getElementsByClassName("mask");
for(i = 0; i < hidemask.length; i++)
    hidemask[i].style.display = "none";

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