create a HTMLCollection

后端 未结 4 1405
半阙折子戏
半阙折子戏 2020-12-01 23:39

I\'m trying to shim Element.prototype.children which should return a HTMLCollection

There is a window.HTMLCollection

However

var h = new HTML         


        
相关标签:
4条回答
  • 2020-12-02 00:18

    Don't expect host objects to behave like (ECMAScript) native objects, they are completely different things. Some browsers do implement their DOM objects like ECMAScript objects, but it is not required and should not be relied upon. Note that most HTML collections are live, it is very difficult to emulate that in a native object.

    0 讨论(0)
  • 2020-12-02 00:18

    I think this is the proper way of creating HTMLCollection, which is handled by the browser.

    var docFragment = document.createDocumentFragment();
    docFragment.appendChild(node1);
    docFragment.appendChild(node2);
    var myHTMLCollection = docFragment.children;
    

    Refs.:

    https://stackoverflow.com/a/35969890/10018427

    https://developer.mozilla.org/en-US/docs/Web/API/NodeList

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

    https://www.w3schools.com/js/js_htmldom_nodelist.asp

    0 讨论(0)
  • 2020-12-02 00:24

    Here's how I would do it:

    function MyHTMLCollection( arr ) {
        for ( var i = 0; i < arr.length; i += 1 ) {
            this[i] = arr[i];
        }
    
        // length is readonly
        Object.defineProperty( this, 'length', {
            get: function () {
                return arr.length;
            }
        });
    
        // a HTMLCollection is immutable
        Object.freeze( this );
    }
    
    MyHTMLCollection.prototype = {
        item: function ( i ) {
            return this[i] != null ? this[i] : null;
        },
        namedItem: function ( name ) {
            for ( var i = 0; i < this.length; i += 1 ) {
                if ( this[i].id === name || this[i].name === name ) {
                    return this[i];
                }
            }
            return null;
        }
    };
    

    where arr is a regular array that contains all the DOM elements which should be inside the HTMLCollection.

    To do list:

    • the argument arr should be checked beforehand: Is it an array? Are all elements of that array DOM elements?
    0 讨论(0)
  • 2020-12-02 00:29

    I know this is an older question but I came across a similar need to create an empty HTMLCollection and I did it by simply creating an element and then running getElementsByClassName() against it using a class that doesn't exist in the element.

    document.createElement("div").getElementsByClassName('noClassHere');
    

    This returns an empty HTMLCollection object.

    0 讨论(0)
提交回复
热议问题