Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

javascript - nodeValue returns null (deep understanding)

The idea was to console log node value. But instead of names it returns null. I don't see why, because code seems fine to me. So, I want understand what happening. I found how to make it work, but I don't understand why my code don't work. Code and results:

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)

Results: link

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When representing HTML elements (DOM Objects) in JavaScript, everything is a node - - even the text within an element. But, not all nodes are elements. So when you got a reference to an <li>, that <li> wasn't the node that contained the name, it was the child text node of that <li>. Another way to say this is that element nodes don't ever have a value of their own, their children do and that is why you were getting null when you tried to get the nodeValue of an <li>

To get that content, you must navigate all the way down to that node:

// 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...