Skip to content

Instantly share code, notes, and snippets.

@Floofies
Last active July 31, 2018 23:31
Show Gist options
  • Save Floofies/b9ac4f6cfe684b7b82857beda40d1605 to your computer and use it in GitHub Desktop.
Save Floofies/b9ac4f6cfe684b7b82857beda40d1605 to your computer and use it in GitHub Desktop.
Testing which Array prototype methods work on NodeList
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<h1>See Console for test results.</h1>
<div id="testNode">
<i></i>
<i></i>
<i></i>
<i></i>
<i class="testClass"></i>
</div>
<script type="text/javascript">
// Calls apply on Array prototype methods, supplying the NodeList as a thisArg:
function apply(testList, method, ...args) {
return Array.prototype[method].apply(testList, args);
}
function test(method, ...args) {
// Create NodeList for testing:
const testList = document.body.querySelector("#testNode").querySelectorAll("i");
console.group(method + " results:");
try {
console.log(apply(testList, method, ...args));
} catch (error) {
console.error(error);
};
console.groupEnd();
}
test("pop");
// TypeError: Cannot assign to read only property 'length' of object '#<NodeList>'
test("keys");
// Array Iterator {}
test("slice", 0, 2);
// (2) [i, i]
test("indexOf", document.querySelector(".testClass"));
// 4
test("find", node => node.className === "testClass");
// <i class=​"testClass">​</i>​
test("join");
// [object HTMLElement],[object HTMLElement],[object HTMLElement],[object HTMLElement],[object HTMLElement]
test("fill", "Hello", 0, 3);
// TypeError: Failed to set an indexed property on 'NodeList': Index property setter is not supported.
test("forEach", node => console.log(node));
// <i>​</i>​ <i>​</i>​ <i>​</i>​ <i>​</i>​ <i class=​"testClass">​</i>​
test("filter", node => node.className === "testClass");
// [i.testClass]
test("map", node => node.cloneNode());
// (5) [i, i, i, i, i.testClass]
test("reverse");
// TypeError: Failed to set an indexed property on 'NodeList': Index property setter is not supported.
test("some", node => node.className === "testClass");
// true
test("every", node => node.tagName === "I");
// true
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment