简体   繁体   中英

Javascript to hide every element in div if it's height is 0

I'm looking for a way to hide every element (set to display:none) in a div (marked with a class or an id) if the height of the element is 0.

Example. Hide elem1 and elem4

<div class="container">
    <ul id="elem1" style="height:0"> ... </ul>
    <ul id="elem2" style="height:50"> ... </ul>
    <ul id="elem3" style="height:40"> ... </ul>
    <ul id="elem4" style="height:0"> ... </ul>
    <ul id="elem5" style="height:60"> ... </ul>
</div>

Please help

Try this one for size:

.container ul[style="height:0"] {
    display: none;
}

Demo: http://jsfiddle.net/qwertynl/yBJEe/


The following will work no matter if there is a space after the : or not:

.container ul[style~="0"], .container ul[style="height:0"] {
    display: none;
}

Demo: http://jsfiddle.net/qwertynl/yBJEe/3/

Pure JS sample. Mark your elements with a class. This will work:

<div class="container">
    <ul class='yourClass' id="elem1" style="height:0">.1..</ul>
    <ul class='yourClass' id="elem2" style="height:50">.2..</ul>
    <ul class='yourClass' id="elem3" style="height:40">.3..</ul>
    <ul class='yourClass' id="elem4" style="height:0">.4..</ul>
    <ul class='yourClass' id="elem5" style="height:60">.5..</ul>
</div>

JS script:

(function hideElements() {

var the_elements = document.getElementsByClassName('yourClass');
for (var i = 0; i < the_elements.length; ++i) {
    var item = the_elements[i];

    if (item.style.height === '0px') {
        item.style.display = 'none';
    }
}
})();

Note that the value retrieved is '0px'. JSFiddle working sample: http://jsfiddle.net/amontellano/EgHLt/5/

This CSS block would help

.container ul {
    overflow: hidden;
}

You can do it like this, using querySelectorAll()

var x = document.querySelectorAll("ul[id*='elem']"); //select all elements with an ID containing 'elem'
for (var i=0; i<x.length; i++) { //loop the element array and check if height == 0
    if (x[i].style.height == 0) x[i].style.display = "none"; //set display to none
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM