Reputation: 5127
I am trying to make display none for all the child nodes of a div. It works well with getElementsByTagname('*')
My Markup
<div id="container">
<div id="child1"></div>
<div id"child2">
<div id="inner-child"></div>
</div>
</div>
I would like to manipulate the display property of only the child1, child2.
function hideAllChildren(){
var elem = document.getElementById("container");
var children = elem.childNodes;
alert("children " + children.length)
for (i=0; i < children.length ;i++)
{
children[i].style.display="none";// Error - children[i].style undefined
}
}
Can you figureout what the issue could be ?
Upvotes: 2
Views: 3607
Reputation: 587
try this
<div id="container">container
<div id="child1">child1</div>
<div id"child2">Child 2
<div id="inner-child">inner-child</div>
</div>
</div>
<div id="clickme">Click me</div>
/// java script
$('#clickme').click(function() {
hideAllChildren();
});
function hideAllChildren(){
var elem = document.getElementById("container");
var children = elem.childNodes;
alert("children " + children.length)
$('#container').hide();
}
Upvotes: 0
Reputation: 15433
Why do you want to hide all the child nodes.
Where you can hide the parent and all the child will automatically hide.
So it will be simply:
function hideAllChildren(){
var elem = document.getElementById("container");
//alert("children " + children.length)
elem.style.display="none";
}
Upvotes: 0
Reputation: 147413
Not all the child nodes are elements, some are text nodes in some browsers and text nodes don't have a style property. Trying to access a property of a non-existant property throws an error.
Either test the node type or that the node has a (non-falsey value for its) style property first:
if (children[i].style) {
children[i].style.display="none";
}
However, you may find it much better to use a class and appropriate CSS rule and just add it to the parent element.
e.g.
<style type="text/css">
.hideAll * {
display: none;
}
</style>
</script type="text/javascript">
<button onclick="
document.getElementById('d0').className = 'hideAll';
">Hide all</button>
<button onclick="
document.getElementById('d0').className = '';
">Show all</button>
<div id="d0">Here is the div
<ul>
<li class="item">apple
<li class="item">orange
<li class="item">banana
</ul>
</div>
Upvotes: 4