这就是其中之一,它看起来很简单,但我想不出一个好的方法来实现它。
我有一个节点,可能是 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/