Skip to content

Instantly share code, notes, and snippets.

@marcoos
Created August 13, 2011 14:59
Show Gist options
  • Save marcoos/1143928 to your computer and use it in GitHub Desktop.
Save marcoos/1143928 to your computer and use it in GitHub Desktop.
createNodeList
/**
* 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;
}
@marcoos
Copy link
Author

marcoos commented Aug 13, 2011

Ok, so it only works with elements, won't work with TextNodes, comments and stuff like that...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment