I want to be able to have a javascript function that hides divs for me. For example, I have something like
<div id='container'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
And i would like the function to hide every 'item' class element after say the first 3. How would i go about this?
Thanks for any help
We hide the divs by adding a CSS class called hidden to the outer div called . text_container . This will trigger CSS to hide the inner div.
To hide an element, set the style display property to “none”. document. getElementById("element"). style.
To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .
In JS, you could do something like this, provided the item divs are the only children of the container div:
var itemDivs = document.getElementById("container").children;
for(var i = 0; i < itemDivs.length; i++) {
if(i > 2) {
itemDivs[i].style.display = 'none';
}
}
Try it here: http://jsfiddle.net/eY9ZD/
Otherwise, you could do this:
var divs = document.getElementById("container").getElementsByTagName("div");
for(var i = 0; i < itemDivs.length; i++) {
if(i > 2 && divs[i].className == 'item') {
itemDivs[i].style.display = 'none';
}
}
Try it here: http://jsfiddle.net/6TcWE/
And finally, if jQuery is an option, there's a one-liner using the gt
selector:
$("#container div.item:gt(2)").hide();
Try it here: http://jsfiddle.net/J8wK6/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With