简体   繁体   English

使用JavaScript隐藏具有相同名称的DIV

[英]Hide DIVs with the same name using Javascript

I want to hide all divs with the name "mask" 我想隐藏所有名称为“ mask”的div

This is my HTML : 这是我的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. 我尝试使用下面的JS代码隐藏“掩码”,但它不适用于所有div,仅适用于第一个div。

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

Is there a way to hide them all by using pure Javascript. 有没有一种方法可以通过使用纯Javascript隐藏它们。 No jQuery. 没有jQuery。

You shouldn't be using duplicate ID's in HTML, consider changing it to a class. 您不应该在HTML中使用重复的ID,请考虑将其更改为类。

If you change id="mask" to class="mask" , then you can do: 如果将id="mask"更改为class="mask" ,则可以执行以下操作:

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: 或对于仍处于困境的浏览器(IE7及更低版本),您可以执行以下操作:

    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. 每个文档的id属性必须唯一。 You can do what you want with a class , perhaps. 也许您可以在class做自己想做的事情。 So you would have multiple div s like so: 因此,您将具有多个div如下所示:

<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. 您不能多次分配相同的ID。

But you can add an attribute class to div with id "mask" Eg: 但是您可以向id为“ mask”的div添加一个属性类,例如:

<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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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