I've written a script, it's goal is to stop displaying images one and two, while allowing image 3 to remain displayed and move into their place. It works fine when I use div Id's instead of div Classes, but I would prefer to use div classes so I can group the elements like this:
function myFunction() {
var y = document.getElementsByClassName("firstimage secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
rather than this (in order to save space should I choose to include more elements):
function myFunction() {
var x = document.getElementById("firstimage");
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var y = document.getElementById("secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
I thought that just changing the div id's to div classes, and the #imagenumber's to .imagenumber's (in addition to the change in the javascript I described above) would work but the script stops working when I do. I need the script to function in the same way that the code I am pasting below does, but with div classes instead of div Id's. Please tell me where I am going wrong.
CSS:
#firstimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: green;
margin-top:20px;
color: white;
}
#secondimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: blue;
margin-top:20px;
color: white;
}
#thirdimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: red;
margin-top:20px;
color: white;
}
HTML:
<button onclick="myFunction()">Try me</button>
<div id="firstimage">
DIV element.
</div>
<div id="secondimage">
A second DIV element.
</div>
<div id="thirdimage">
A third DIV element.
</div>
Javascript:
function myFunction() {
var x = document.getElementById("firstimage");
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var y = document.getElementById("secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
getElementsByClassName
, then examine the variabley
. Then try examiningy.style
. You should be able to figure out what's happening quite quickly. Or, you could search forgetElementsByClassName not working
on SO, since there are many questions on the topic here, starting six years ago. – Names