Created
August 13, 2011 14:59
-
-
Save marcoos/1143928 to your computer and use it in GitHub Desktop.
createNodeList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok, so it only works with elements, won't work with TextNodes, comments and stuff like that...