HTMLCollection对象

324 阅读1分钟

HTMLCollection对象是一个类数组,有length属性,单数不能直接调用数组的方法,需要通过call或者apply方法转换成真正的数组之后再调用数组方法。这次想说的是它自带的另外两个函数。

  • item()函数
HTMLCollection对象可以调用item()方法,通过序号来获取特定的某个节点,超过索引则返回 null,例:

 <div id="main">
    <p class="first">first</p>
    <p class="second">second</p>
    <p class="third">third</p>
    <p class="fourth">fourth</p>
 </div>
 <script>
  let main = document.getElementById('main').children
  console.log(main.item(0))
  console.log(main.item(2))
 </script> 
 
通过item()函数获取第一位和第三位子元素,输出的结果为:
<p class="first">first</p>
<p class="third">third</p>
  • namedItem()函数
namedItem()函数用来返回一个节点。首先使用id属性去匹配,然后如果没有匹配到则使用name属性去匹配,如果还是没有匹配到则返回 null。当出现重复的id或者name属性时,只返回匹配到的第一个值,例:

 <div id="main">
    <input type="text" id="username"/>
    <input type="text" name="username"/>
    <input type="text" name="password"/>
 </div>
 <script>
  let main = document.getElementById('main').children
  console.log(main.namedItem('username'))
  console.log(main.namedItem('password'))
 </script> 
 
最后,输出的结果为:
<input type="text" id="username"/>
<input type="text" name="password"/>

NodeList对象也具有length属性,返回集合的长度,也同样具有item()函数,通过索引定位子元素的位置,使用方法类似。但是NodeList对象没有namedItem()函数。生成NodeList对象的方法:querySelector getElementsByName,生成HTMLCollection对象的方法:getElementsByClassName getElementsByTagName。另外使用.children得到的元素集合也是HTMLCollection对象。