-1

这个想法是控制台日志节点值。但它返回的不是名称,而是 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)

结果: 链接

4

2 回答 2

3

在 JavaScript 中表示 HTML 元素(DOM 对象)时,一切都是节点——甚至是元素中的文本。但是,并非所有节点都是元素。因此,当您获得对 an 的引用时<li>,它<li>不是包含名称的节点,而是 that 的子文本节点<li>。另一种说法是元素节点从来没有自己的价值,他们的孩子有,这就是为什么null当你试图nodeValue获得<li>

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

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

.textContent但是,DOM 还公开了其他方法,可以通过and直接访问元素内的内容.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>

于 2017-05-05T16:23:48.133 回答
0

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

于 2017-05-05T16:22:37.593 回答