How to check if an element matches the :empty pseudo-class in pure JS?


Tags: javascript,html,css,css3,css-selectors

Problem :

How can I check, in pure JavaScript (no jQuery, no libraries), if a given HTML element is empty? My definition of "empty" is the same as the CSS :empty pseudo-class. So, if a given element would match the :empty selector, then I want to know about it.



Solution :

function isEmpty (el) {
    if (!el.hasChildNodes()) return true;

    for (var node = el.firstChild; node = node.nextSibling;) {
        var type = node.nodeType;
        if (type === 1 && !isEmpty(node) || // another element
            type === 3 && node.nodeValue) { // text node
            return false;
        }
    }
    return true;
}

As per the CSS spec, this will return true if the given element has no non-empty child nodes. Long-awaited JSFiddle demo available.


    CSS Howto..

    how to stick the footer to the bottom of the page while moving it upward in a parallax-like effect?

    How to prevent this css shape to scroll left and right

    how to make a css gradient stop after so many pixels?

    How to Protect an HTML element from it's respective assigned CSS

    How can I set a CSS property on the html element with jQuery?

    I need a max-margin CSS property, but it doesn't exist. How could I fake it?

    How to put the menu over the content?

    How to apply css selector in ZK

    showing a css component for a specified number of seconds

    How to stop jitter of relatively placed items on scrolling with mouse?

    how to set the font-family like a digital clock CSS? [closed]

    How to force the casing of letters in a textbox

    How to test print output of browsers with online tools?

    How to add text underneath the centered image

    How to save the state of css background-color property change when navigating away from one menu to another

    CSS - How to address only parents and not children

    How to add shadow 'wings' to a centered content div

    How to cancel specific one element at external CSS?

    How to “reset” style in view page, set in css file

    how to horizontally center a div of 10000px (wider than full screen) in CSS?

    How to align columns in bootstrap to center?

    How to reset css (a:visited{color:green}) when refresh browser address bar

    HTML: slideshow is not recognised as an element in the main content of the page

    How to DRY Sass code using variables?

    how to make a navigation 100% width within an header wrapper

    How to fix this css float problem?

    Modernizr: how do I detect CSS display:table-cell support?

    How to place a button in the middle of the page using HTML and CSS

    How to change color of Bootstrap warning class table row

    How can I remove vertical padding from ionic icon?