parentNode,parentElement,childNodes,children的区别

从字面上我们可以知道一个是parent的节点,一个是parent的元素,实际上在很多时候它们的返回的内容是相同的,比如有这么一段代码:

<!DOCTYPE html>
<html>
<head>
  <title>节点</title>
</head>
<body>
  <ul>
    <li id="item1">item1
     <ul>
      <li>item i</li>
      <li>item ii</li>
      <li>item iii</li>
     </ul>
    </li>
    <li>item2</li>
    <li>item3</li>
 </ul>
 
<script>
 var item1 = document.getElementById('item1');
 console.log(item1.parentNode);
 console.log(item1.parentElement);
</script>
</body>
</html>
 
 
此时我们我们打印出来的结果是相同的

但是如果我们继续往上查找父级
<script>
 console.log(item1.parentNode.parentNode.parentNode.parentNode);   console.log(item1.parentElement.parentElement.parentElement.parentElement);
</script>

最终我们看到这样的结果

因此我们知道parentElement查找的是父级元素,如果有返回元素节点,否则返回null,而parentNode此时返回的是document节点
 
<script>
 console.log(item1.childNodes);
 console.log(item1.children);
</script>

这里的childNodes返回的是子节点,其中包括空格,换行,元素,而children则返回的是子元素

我们可以通过nodeValue更直观的查看打印的内容,注意:元素节点没有nodeValue
<script>
 console.log(item1.childNodes[0].nodeValue);   
 console.log(item1.children[0].nodeName);
</script>



我们通过选中部分可以看出这里打印包括空格和换行,而元素节点的nodeValue则为null
其中
节点树:
父子关系:
parentNode, childNode, firstChild, lastChild
 
兄弟关系:
previousSibling, nextSibling
 
元素树:
父子关系:
parentElement, children, firstElementChild, lastElementChild
 
兄弟关系:
previousElementSibling, nextElementSibling
这些规则和上述内容都是相同的
 
 

猜你喜欢

转载自blog.csdn.net/coding_1/article/details/78202693
今日推荐