createNodeList(array)
Create a NodeList from an array of arbitrary elements.
by marcoos
HTML
<p>Hello.</p>
JavaScript
/**
* Creates a NodeList from an array
*
* @param elements {Array} - array of elements from the same document
* @throws {TypeError} - if elements are from different documents
*
* @returns {NodeList}
*/
function createNodeList(elements) {
var nodeList, ownerDocument, firstElement, klass;
// temporary class name
klass = "cnl__" + parseInt(1000000 * Math.random(), 10).toString(16);
// force elements to be an array
elements = Array.prototype.slice.call(elements);
firstElement = elements[0];
ownerDocument = firstElement.ownerDocument;
// make sure the elements come from the same document
if (!elements.every(function (element) {
return element.ownerDocument === ownerDocument;
})) {
throw new TypeError("Can't create a NodeList from elements from different documents!");
}
// add a temporary class to each of the elements
elements.forEach(function (element) {
element.classList.add(klass);
});
// find the elements with the temporary class
// querySelectorAll returns a static NodeList
nodeList = ownerDocument.querySelectorAll("." + klass);
// remove the temporary class
Array.forEach(nodeList, function (element) {
element.classList.remove(klass);
});
return nodeList;
}
(function () {
var nl = createNodeList([document.body, document.body.firstElementChild, document.head]);
console.log(nl, nl.length, nl.item(0), nl[1]);
console.log(nl instanceof NodeList);
}());