【问题标题】:nodeValue returns null (deep understanding)nodeValue 返回null(深入理解)
【发布时间】:2017-05-05 16:17:47
【问题描述】:

这个想法是控制台日志节点值。但它返回的不是名称,而是 null。我不明白为什么,因为代码对我来说似乎很好。所以,我想了解发生了什么。我找到了如何使它工作,但我不明白为什么我的代码不起作用。代码和结果:

HTML

 <div>Users:</div>
  <ul id="myList">
    <li>John</li>
    <li>Doe</li>
  </ul> 

JavaScript

let listNode = document.body.children[1].children[1]

console.log(listNode)

// Why not return node value?
let value = listNode.nodeValue
console.log(value)

结果: link

【问题讨论】:

    标签: javascript nodevalue


    【解决方案1】:

    当在 JavaScript 中表示 HTML 元素(DOM 对象)时,一切都是节点——甚至是元素中的文本。 But, not all nodes are elements. 因此,当您获得对 &lt;li&gt; 的引用时,&lt;li&gt; 不是包含该名称的节点,而是该 &lt;li&gt; 的子文本节点。另一种说法是元素节点从来没有自己的价值,他们的孩子有,这就是为什么当你试图获得nodeValue&lt;li&gt;时你得到null的原因

    要获取该内容,您必须一直向下导航到该节点:

    // Get a node list of all the <li> child elements in the #myList list:
    let listNodes = document.querySelectorAll("#myList > li");
    
    // Go to the first <li> in the node list and then navigate the the text node contained within that node
    let value = listNodes[0].firstChild.nodeValue;
    console.log("The <li>.firstChild node value is: " + value);
    console.log("The <li> node type is: " + listNodes[0].nodeType + " (1 = element node)");
    console.log("The <li>.firstChild node type is: " + listNodes[0].firstChild.nodeType + " (3 = text node)");
    <div>Users:</div>
     <ul id="myList">
        <li>John</li>
        <li>Doe</li>
     </ul>

    但是,DOM 还通过 .textContent.innerHTML 公开了其他直接访问元素内内容的方法:

    // Get a node list of all the <li> child elements in the #myList list:
    let listNodes = document.querySelectorAll("#myList > li");
    
    // .textContent allows you to extract the text of an element without navigating 
    // into its text node
    let value = listNodes[1].textContent;
    console.log(value);
    
    // While .innerHTML allows you to acces the HTML within an element:
    value = listNodes[1].innerHTML;
    console.log(value);
    <div>Users:</div>
     <ul id="myList">
        <li>John</li>
        <li><a href="">Doe</a></li>
     </ul>

    【讨论】:

      【解决方案2】:

      因为您的li 中的Done 是一个节点,所以文本也是节点,而不仅仅是HTML 标签

      更新后的代码:

      let listNode = document.body.children[1].children[1]
      
      console.log(listNode)
      
      // Why not return node value?
      let value = listNode.childNodes[0].nodeValue;
      console.log(value)
      <div>Users:</div>
        <ul id="myList">
          <li>John</li>
          <li>Doe</li>
        </ul>

      【讨论】: