Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript hiding divs

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

like image 910
Dori Avatar asked Jul 26 '10 15:07

Dori


People also ask

How do I hide a div?

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.

How do I hide a specific div in HTML?

To hide an element, set the style display property to “none”. document. getElementById("element"). style.

How do you hide a div until a button is clicked?

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 .


1 Answers

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/

like image 132
karim79 Avatar answered Sep 22 '22 00:09

karim79