rvighne
rvighne

Reputation: 21897

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

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.

Upvotes: 2

Views: 1709

Answers (4)

rvighne
rvighne

Reputation: 21897

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.

Upvotes: 5

ryanve
ryanve

Reputation: 52531

A way to ensure spec compliance is to use .querySelectorAll or .matches.

function matches(el, selector) {
  return !!~[].indexOf.call(el.ownerDocument.querySelectorAll(selector));
}

Depending on browser support needs, .matches is more direct and even works on detached nodes:

function matches(el, selector) {
  return !!(el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector).call(el, selector);
}

Use either of those like:

matches(el, ':empty')

Upvotes: 4

BoltClock
BoltClock

Reputation: 723809

As far as I know, jQuery's implementation of :empty matches the spec exactly, so it can be used as a reference. From the latest version as of this writing:

"empty": function( elem ) {
    // http://www.w3.org/TR/selectors/#empty-pseudo
    // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
    //   not comment, processing instructions, or others
    // Thanks to Diego Perini for the nodeName shortcut
    //   Greater than "@" means alpha characters (specifically not starting with "#" or "?")
    for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
        if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
            return false;
        }
    }
    return true;
}

Upvotes: 1

Adesh Pandey
Adesh Pandey

Reputation: 769

I think the simplest and easiest way to do this is :

    elem = document.getElemntById('id_of_the_elem');
    function isEmpty(elem){
        if(elem.innerHTML=='') console.log("empty tag");
        else console.log('Non empty tag');
    } 

Upvotes: -1

Related Questions