Javascript Hide Show getElementById vs getElementByClassName

I have a very simple working function to show a div by clicking a link:

function show() {
document.getElementById('box').style.display="block";
}

<a href="javascript:show();">Show</a>
<div id="box" style="display:none;">
Lorem Ipsum
</div>

      

But now when I just change the div from id to class and replace getElementById with getElementByClassName, it doesn't work anymore:

function show() {
document.getElementByClassName('box').style.display="block";
}

<a href="javascript:show();">Show</a>
<div class="box" style="display:none;">
Lorem Ipsum
</div>

      

What am I doing wrong?

+3


source to share


5 answers


This is what the script should look like in principle:

function show() {
    var boxes = document.getElementsByClassName('box');
    for (var i=0; i<boxes.length; i++) {
        boxes[i].style.display = 'block';
    }
}

      

...
EDIT : Whether IE8 does not support getElementsByClassName

. If you want to inject the code for this browser that you have to use, this is the script you have to use:



function show() {
    var boxes = document.querySelectorAll('.box');   // mind the dot
    for (var i=0; i<boxes.length; i++) {
        boxes[i].style.display = 'block';
    }
} 

      

...
getElementById

IE8 is supported as well getElementsByTagName

for your information.

0


source


try this:

function show() {
for(var i=0;i<document.getElementsByClassName('box').length;i++){
document.getElementsByClassName('box')[i].style.display="block";
}
}

      



PS: NOTE s in getElement s ByClassName

+1


source


try it

document.getElementsByClassName('box')[0].style.display="block";
                   ^                   ^

      

for the 1st element of this class

check document.getElementsByClassName

0


source


You just need to replace getElementByClassName

with getElementsByClassName

.

0


source


This is getElementsByClassName

var classInstances = document.getElementsByClassName("box");
var n;
for (n = 0; n < classInstances.length; n++) {
   classInstances[n].style.display="block";
}

      

So you forgot s And if you think about it, it's pure logic.

id is a unique identification number. the class, on the contrary, is not unique , there may be more of them. So it makes sense that you should find them all and iterate over them to get the correct one.

-1


source







All Articles