Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect if an html element can append child nodes?

I created a custom jquery event called 'loading' in my application. I want to append a masking element with a spinner, when this event is triggered. I can figure out that part without problems. However, some elements (images, form inputs, etc..) cannot append child elements. I need to be able to detect if the target of this event can receive child elements. If it cannot, then I will add the spinner & mask to it's parent element.

like image 411
demersus Avatar asked Jun 22 '12 18:06

demersus


2 Answers

You have to check the name:

/*global $, jQuery */

function isVoid(el) {
    var tags = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
                 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'],
        i = 0,
        l,
        name;

    if (el instanceof jQuery) {
        el = el[0];
    }

    name = el.nodeName.toLowerCase();

    for (i = 0, l = tags.length; i < l; i += 1) {
        if (tags[i] === name) {
            return true;
        }
    }
    return false;
}

And use it like this:

var el = document.getElementById('el'),
    elj = $('#el');

if (!isVoid(el)) {
    // append
}
like image 69
jasssonpet Avatar answered Sep 29 '22 01:09

jasssonpet


You can add child elements, they just won't render. This may sound like a semantic distinction, but it's critical to your problem: the DOM doesn't know whether a particular tag is rendered or not.

Your best bet is just to check manual:

var allowChildren = function(elem) {
   return ! (elem.nodeName in { INPUT : true, IMG : true }) ;
};
like image 22
Michael Lorton Avatar answered Sep 29 '22 01:09

Michael Lorton