rainerbrunotte rainerbrunotte - 3 months ago 13
HTML Question

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 simply change the div from an id to a class and replace getElementById to getElementByClassName, it does not 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?

Answer

This is what the script in principle should look like:

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

.
EDIT: Be it that IE8 doesn't support getElementsByClassName. If you want to code for that browser as well, which you should imo, this is the script you should 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 is supported by IE8, just as getElementsByTagName, for your information.