chaining getElementById

前端 未结 6 1706
盖世英雄少女心
盖世英雄少女心 2020-11-29 12:27

I\'ve been looking for an answer to this question but I could find none so I thought I\'d try StackOverflow.

In javascript, is this valid:

x = document

6条回答
  •  天涯浪人
    2020-11-29 12:35

    Nope.

    ...But you can, though:

    Element.prototype.getElementById = function(id) {
        return document.getElementById(id);
    }
    

    Try it on this page:

    var x = document.getElementById('footer').getElementById('copyright');
    

    Edit: As Pumbaa80 pointed out, you wanted something else. Well, here it is. Use with caution.

    Element.prototype.getElementById = function(req) {
        var elem = this, children = elem.childNodes, i, len, id;
    
        for (i = 0, len = children.length; i < len; i++) {
            elem = children[i];
    
            //we only want real elements
            if (elem.nodeType !== 1 )
                continue;
    
            id = elem.id || elem.getAttribute('id');
    
            if (id === req) {
                return elem;
            }
            //recursion ftw
            //find the correct element (or nothing) within the child node
            id = elem.getElementById(req);
    
            if (id)
                return id;
        }
        //no match found, return null
        return null;
    }
    

    An example: http://jsfiddle.net/3xTcX/

提交回复
热议问题