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

后端 未结 4 405
轻奢々
轻奢々 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条回答
  •  悲&欢浪女
    2020-12-08 10:18

    Since it seems that creating a real NodeList from an array is having severe fallbacks, maybe you could use a regular JS object with a self-made prototype to emulate a NodeList instead. Like so:

    var nodeListProto = Object.create({}, {
            item: {
                value: function(x) {
                    return (Object.getOwnPropertyNames(this).indexOf(x.toString()) > -1) ? this[x] : null;
                },
                enumerable: true
            },
            length: {
                get: function() {
                    return Object.getOwnPropertyNames(this).length;
                },
                enumerable: true
            }
        }),
        getNodeList = function(nodes) {
            var n, eN = nodes.length,
                list = Object.create(nodeListProto);
            for (n = 0; n < eN; n++) { // *
                Object.defineProperty(list, n.toString(), {
                    value: nodes[n],
                    enumerable: true
                });
            }
            return list;
        };
    // Usage:
    var nodeListFromArray = getNodeList(arrayOfNodes);
    

    There are still some fallbacks with this solution. instanceof operator can't recognize the returned object as a NodeList. Also, console loggings and dirrings are shown differently from a NodeList.

    (* = A for loop is used to iterate the passed array, so that the function can accept a passed NodeList too. If you prefer a forEach loop, that can be used as well, as long as an array only will be passed.)

    A live demo at jsFiddle.

提交回复
热议问题