2017-05-05 3 views
-1

아이디어는 로그 노드 값을 콘솔하는 것이 었습니다. 하지만 이름 대신 null을 반환합니다. 이유는 모르겠지만 코드가 나에게 잘 보이기 때문입니다. 그래서, 무슨 일이 일어 났는지 이해하고 싶습니다. 어떻게 작동시키는 지 발견했지만 코드가 작동하지 않는 이유를 모르겠습니다. 코드 및 결과 :nodeValue가 null을 반환 함 (깊은 이해)

HTML

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

자바 스크립트

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

console.log(listNode) 

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

결과 : 당신의 liDone가 노드이기 때문에 link

답변

2

자바 스크립트에서 HTML 요소 (DOM 개체)를 나타내는, 모든 노드입니다 - - 요소 내에서 심지어는 텍스트입니다. But, not all nodes are elements.<li>에 대한 참조가있는 경우 <li>은 이름이 포함 된 노드가 아니기 때문에 <li>의 자식 텍스트 노드였습니다. 당신이 그 내용을 얻기 위해 <li>

nodeValue를 얻기 위해 시도 할 때 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은 또한 를 통해 요소 내에 컨텐츠로 바로 이동하기 위해 다른 방법을 노출 : 해당 노드까지 모든 방법을 탐색한다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

는, 텍스트 노드도뿐만 아니라 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>

관련 문제