javascript - 从 JavaScript 中的单个节点创建节点列表

标签 javascript nodes nodelist

这就是其中之一,它看起来很简单,但我想不出一个好的方法来实现它。

我有一个节点,可能是 nodelist = document.getElementById("mydiv"); - 我需要将其标准化为节点列表。也不是数组:一个实际的、真正的 nodeList 对象。

nodelist = [document.getElementById("mydiv")];

请不要使用图书馆。

最佳答案

获取任何已在 JavaScript 中引用的元素,为其提供一个我们可以使用选择器找到的属性,将其作为列表找到,删除属性,返回列表。

function toNodeList(elm){
    var list;
    elm.setAttribute('wrapNodeList','');
    list = document.querySelectorAll('[wrapNodeList]');
    elm.removeAttribute('wrapNodeList');
    return list;
}

从 bfavaretto 的回答扩展而来。


function toNodeList(elm, context){
    var list, df;
    context = context // context provided
           || elm.parentNode; // element's parent
    if(!context && elm.ownerDocument){ // is part of a document
        if(elm === elm.ownerDocument.documentElement || elm.ownerDocument.constructor.name === 'DocumentFragment'){ // is <html> or in a fragment
            context = elm.ownerDocument;
        }
    }
    if(!context){ // still no context? do David Thomas' method
        df = document.createDocumentFragment();
        df.appendChild(elm);
        list = df.childNodes;
        // df.removeChild(elm); // NodeList is live, removeChild empties it
        return list;
    }
    // selector method
    elm.setAttribute('wrapNodeList','');
    list = context.querySelectorAll('[wrapNodeList]');
    elm.removeAttribute('wrapNodeList');
    return list;
}

最近想到了另一种方法

var _NodeList = (function () {
    var fragment = document.createDocumentFragment();
    fragment.appendChild(document.createComment('node shadows me'));
    function NodeList (node) {
        this[0] = node;
    };
    NodeList.prototype = (function (proto) {
        function F() {} // Object.create shim
        F.prototype = proto;
        return new F();
    }(fragment.childNodes));
    NodeList.prototype.item = function item(i) {
        return this[+i || 0];
    };
    return NodeList;
}());

现在

var list = new _NodeList(document.body); // note **new**
list.constructor === NodeList; // all these are true
list instanceof NodeList;
list.length === 1;
list[0] === document.body;
list.item(0) === document.body;

关于javascript - 从 JavaScript 中的单个节点创建节点列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13351966/

相关文章:

javascript - 与多个 if 语句相比,array.includes 对性能有负面影响吗?

javascript - 如何检查来自用户收件箱的网页请求

c - 将节点插入排序的链表的函数

c++ - 如何在 Maya API 中从 MObject 获取 Node 类实例

c - 删除第一个节点并取出头节点数据

javascript - 转换脚本以独立处理多个表

javascript - 如何在HTML中插入两个js文件?

javascript - 使用 PowerShell 自动压缩 JavaScript

multiprocessing - 将节点进程与 MPI 和 FORTRAN 一起分类

javascript - 创建一个函数来获取选择器,就像 jquery 使用纯 javascript 所做的那样