How can I convert an Array of nodes to a static NodeList?

后端 未结 4 406
轻奢々
轻奢々 2020-12-08 10:02

NOTE: Before this question is assumed a duplicate, there is a section at the bottom of this question that addresses why a few similar questions do not provide the answer

4条回答
  •  猫巷女王i
    2020-12-08 10:13

    Here are my two cents:

    • Document is a native object and extending it may not be a good idea.
    • NodeList is a native object with a private constructor and no public methods to add elements, and there must be a reason for it.
    • Unless someone is able to provide a hack, there is no way to create and populate a NodeList without modifying the current document.
    • NodeList is like an Array, but having the item method that works just like using square brackets, with the exception of returning null instead of undefined when you are out of range. You can just return an array with the item method implemented:

    myArray.item= function (e) { return this[e] || null; }

    PS: Maybe you are taking the wrong approach and your custom query method could just wrap a document.querySelectorAll call that returns what you are looking for.

提交回复
热议问题