如何在JavaScript

时间:2017-10-26 13:49:13

标签: javascript html hide

我试图隐藏这个div类的可见性,但是我写的javascript代码没有用。在这种情况下我该怎么办?

<div class="form-item webform-component webform-component-display webform-component--1-contact-1-bg20-custom-4">
  <label>Question? </label>
 Nein
</div>



<script>
document.getElementsByClassName("form-item webform-component webform-component-display webform-component--1-contact-1-bg20-custom-4").style.visibility = '"hidden";
</script>

2 个答案:

答案 0 :(得分:1)

有三件事

  1. 它不是一个有空格的类名,它是一个div中的四个不同的类

  2. 您在双cotes之前已经提出了额外的单引号。

  3. getElementsByCLassName返回一个数组,因此您需要指定索引

  4. 理想情况下应该如此

    &#13;
    &#13;
    <div class="form-item webform-component webform-component-display webform-component--1-contact-1-bg20-custom-4">
    <label>Question? </label>
    Nein
    </div>
    
    
    <script>
    document.getElementsByClassName("form-item")[0].style.visibility = "hidden";
    </script>
    &#13;
    &#13;
    &#13;

    或者如果我们按照你的方式写下来

    &#13;
    &#13;
    <div class="form-item webform-component webform-component-display webform-component--1-contact-1-bg20-custom-4">
    <label>Question? </label>
    Nein
    </div>
    
    
    <script>
    document.getElementsByClassName("form-item webform-component webform-component-display webform-component--1-contact-1-bg20-custom-4")[0].style.visibility = "hidden";
    </script>
    &#13;
    &#13;
    &#13;

    您缺少在getElementsByClassName和其他'

    之后指定的索引

答案 1 :(得分:0)

document.getElementsByClassName会返回一个元素数组。因此,如果您确定只有一个具有该类组合的元素,那么您可以尝试

 document.getElementsByClassName
 ("form-item webform-component webform-component-display 
   webform-component--1-contact-1-bg20-custom-4")[0].style.visibility = "hidden";