I am trying to create an array of a parent div's (id="lol"
) children and them fetch them to change display:none;
except for the child with id="a"
. I've tried this but it doesn't work. How can I improve this to get it to work?
function myFunction() {
var x = document.getElementById('a');
var children = [].slice.call(document.getElementById('lol').getElementsByTagName('*'),0);
var arrayLength = children.length;
for (var i = 0; i < arrayLength; i++) {
var name = children[i].getAttribute('id');
var z = document.getElementById(name);
z.style.display = 'none';
}
x.style.display = 'block';
}
If every child has an id
attribute than it will work. Otherwise, some children might not have id
attribute, in that case variable z
will be undefined
and accessing style
property over z
which is undefined
will give error. Simple fix would be just handling undefined
variable:
if(z)
z.style.display = 'none';
Same goes with variable x
, too.