NodeList-Iterable.html (2003B)
1 <!doctype html> 2 <meta charset="utf-8"> 3 <title>NodeList Iterable Test</title> 4 <script src="/resources/testharness.js"></script> 5 <script src="/resources/testharnessreport.js"></script> 6 <p id="1"></p> 7 <p id="2"></p> 8 <p id="3"></p> 9 <p id="4"></p> 10 <p id="5"></p> 11 12 <div id="live"><b id="b1">1</b><b id="b2">2</b><b id="b3">3</b></div> 13 <script> 14 var paragraphs; 15 setup(function() { 16 paragraphs = document.querySelectorAll('p'); 17 }) 18 test(function() { 19 assert_true('length' in paragraphs); 20 }, 'NodeList has length method.'); 21 test(function() { 22 assert_true('values' in paragraphs); 23 }, 'NodeList has values method.'); 24 test(function() { 25 assert_true('entries' in paragraphs); 26 }, 'NodeList has entries method.'); 27 test(function() { 28 assert_true('forEach' in paragraphs); 29 }, 'NodeList has forEach method.'); 30 test(function() { 31 assert_true(Symbol.iterator in paragraphs); 32 }, 'NodeList has Symbol.iterator.'); 33 test(function() { 34 var ids = "12345", idx=0; 35 for(var node of paragraphs){ 36 assert_equals(node.getAttribute('id'), ids[idx++]); 37 } 38 }, 'NodeList is iterable via for-of loop.'); 39 40 test(function() { 41 assert_array_equals(Object.keys(paragraphs), ['0', '1', '2', '3', '4']); 42 }, 'NodeList responds to Object.keys correctly'); 43 44 test(function() { 45 var container = document.getElementById('live'); 46 var nodeList = container.childNodes; 47 48 var ids = []; 49 for (var el of nodeList) { 50 ids.push(el.id); 51 assert_equals(el.localName, 'b'); 52 if (ids.length < 3) { 53 var newEl = document.createElement('b'); 54 newEl.id = 'after' + el.id; 55 container.appendChild(newEl); 56 } 57 } 58 59 assert_array_equals(ids, ['b1', 'b2', 'b3', 'afterb1', 'afterb2']); 60 }, 'live NodeLists are for-of iterable and update appropriately'); 61 </script>