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?
source to share
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.
source to share
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.
source to share