2017-05-05 57 views
-1

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

回答

2

当表示在JavaScript的HTML元素(DOM对象),一切是一个节点 - - 甚至一个元素中的文本。 But, not all nodes are elements.因此,当您获得对<li>的引用时,该<li>不是包含该名称的节点,而是该<li>的子文本节点。说这是元素节点永远不要有自己的价值的另一种方式,他们的孩子做的,这就是为什么你越来越null当你试图让一个<li>

nodeValue要获得这些内容,必须导航一路下跌到该节点:

// 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中也暴露了其他的方式通过直来直去的内容元素中3210.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>

0

因为Doneli是一个节点,文本是节点也不仅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>