13

HTMLCollectionElement.prototype.childrenを返す必要があるシムをしようとしています

ありますwindow.HTMLCollection

でも

var h = new HTMLCollection();
//TypeErrror: HTMLCollection is not a constructor

var h = Object.create(HTMLCollection.prototype);
h[0] = div;
h.item(0); 
// Could not convert JavaScript argument

Firefox7とChromeをテストする

シミングとは別に、HTMLCollectionそれと相互作用する方法はありますか?

解決策を提案できる場合は、このgithubの問題に関するフィードバックも提供してください

4

4 に答える 4

9

これが、ブラウザで処理されるHTMLCollectionを作成する適切な方法だと思います。

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

参照:

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

于 2019-11-28T16:01:39.467 に答える
7

これが私がそれをする方法です:

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;
    }
};

ここarrで、はHTMLCollection内にある必要があるすべてのDOM要素を含む通常の配列です。

リストを行うには:

  • 引数arrは事前にチェックする必要があります:それは配列ですか?その配列のすべての要素はDOM要素ですか?
于 2011-10-13T13:18:47.760 に答える
6

ホストオブジェクトが(ECMAScript)ネイティブオブジェクトのように動作することを期待しないでください。それらは完全に異なるものです。一部のブラウザはECMAScriptオブジェクトのようなDOMオブジェクトを実装しますが、これは必須ではなく、信頼すべきではありません。ほとんどのHTMLコレクションはライブであることに注意してください。ネイティブオブジェクトでそれをエミュレートすることは非常に困難です。

于 2011-10-13T12:53:17.913 に答える
2

これは古い質問ですが、空のHTMLCollectionを作成する同様の必要性に遭遇しました。要素を作成し、要素に存在しないクラスを使用してgetElementsByClassName()を実行するだけでそれを実行しました。

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

これにより、空のHTMLCollectionオブジェクトが返されます。

于 2017-11-14T17:02:42.150 に答える