当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Trying to display none, only hiding first instance of div

问题描述:

I have dynamically generated content which I'm outputting using two divs:

<div id="data1">Some info</div> -- <div id="data2">different info</div>

I want to only show "data2" in certain instances, so I'm trying to use JavaScript to hide it when it's not needed. Basically, my code is:

var getDivs = document.getElementById('data2');

IF STATEMENT {

getDivs.style.display='none'; }

However, this is only kind of working - it's hiding the very first div that it comes across, but it's not hiding ALL of the divs with that ID.

This means that my code is basically correct - the IF STATEMENT is working, the display='none' DOES hide something, it's just not hiding everything that it should...

I tried to change it from div id= to div class= and instead use document.getElementByClassName('data2') but that doesn't seem to be working at all - it doesn't even hide the first .

What am I missing / doing wrong? What do I need to change to get this to hide all of the divs that are "data2"?

Thanks!

网友答案:

Your code seems fine. You can see it works: http://js.do/code/zeek

Later Edit: Using class instead of id:

<div id="data1">Some info</div> -- 
<div class="data2">different info</div>
<div class="data2">different info</div>
<div class="data2">different info</div>


<script type="text/javascript">
 var getDivs = document.getElementsByClassName('data2');
 for(var i= 0; i< getDivs.length; i++){
    var div = getDivs[i];
    div.style.display='none';
 }
</script>
网友答案:

Use jQuery and select by class instead of by ID. See http://api.jquery.com/class-selector.

jQuery is not only easy and readable, you'll also not write getElementByClassName instead of getElementsByClassName.

网友答案:

$('#data2').hide();

This assumes jQuery is on your page: http://api.jquery.com/

Note: You're going to have problems if this is dynamic and there are several elements with the ID of data2. Instead, use classes for selecting relevant divs if you can help it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: