BradShaw
BradShaw

Reputation: 35

DOM returned value for childNode

Here is the HTML:

<ul class="drum">
 <li>A<span>span text A</span></li>
 <li>S<span>span text S</span></li>
 <li>D<span>span text D</span></li>
</ul>

Here is the JS:

let ul = document.querySelectorAll('.drum li');
let ulLen = ul.length;
let arr = [];  
for(var i=0; i<ulLen; i++) {
 if(ul[i].childNodes[0] === '\"S\"') {
  console.log('why is this not returning?');
 }
}

I am trying to match the childnode value of S. When I console.log the ul[i].childNodes[0] I can see the return value to be "S" but I am just not understanding why the if condition is not being satisfied. What am I missing? I have also tried the firstChild property, but still can't satisfy the condition.

Upvotes: 0

Views: 32

Answers (1)

Musa
Musa

Reputation: 97717

You are comparing a Node to a string, you have to get the text content of the node then do the comparison. Also, remove the double quotes.

let ul = document.querySelectorAll('.drum li');
let ulLen = ul.length;
let arr = [];  
for(var i=0; i<ulLen; i++) {
 if(ul[i].childNodes[0].textContent === 'S') {
  console.log('why is this not returning?');
 }
}
<ul class="drum">
 <li>A<span>span text A</span></li>
 <li>S<span>span text S</span></li>
 <li>D<span>span text D</span></li>
</ul>

Upvotes: 2

Related Questions