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

后端 未结 4 767
感情败类
感情败类 2021-01-11 10:20

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 tha

相关标签:
4条回答
  • 2021-01-11 11:19

    http://jsfiddle.net/mblase75/eGyRH/3/ -- Chrome lets me add a child element to an <input> tag, even though it's not displayed at all. It's visible in the DOM debugger, just not in the browser window.

    However, I can test it's .width() and see that's equal to zero or not: http://jsfiddle.net/mblase75/eGyRH/4/

    alert($('.element').append('<span>asdf</span>').children().width());​
    

    However, this will also be zero width if, for instance, I'm adding the span to a hidden div: http://jsfiddle.net/mblase75/eGyRH/5/ -- so it's not totally reliable either.

    0 讨论(0)
  • 2021-01-11 11:21

    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 }) ;
    };
    
    0 讨论(0)
  • 2021-01-11 11:21

    The accepted answer has a very nice fuction based on which types of nodes can be void. It can be replaced by a jQuery one-liner:

    node.is("area,base,br,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr")

    0 讨论(0)
  • 2021-01-11 11:22

    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
    }
    
    0 讨论(0)
提交回复
热议问题