DOM返回childNode的值

时间:2018-12-09 22:09:56

标签: javascript dom

这是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>

这是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?');
 }
}

我试图匹配childnode的{​​{1}}值,当我console.log S.时,我看到返回值是“ S”,但我只是不明白为什么ul[i].childNodes[0]条件未得到满足。我想念什么?我也尝试过if属性,但仍然不能满足条件。

1 个答案:

答案 0 :(得分:2)

您正在将节点与字符串进行比较,您必须获取节点的文本内容然后进行比较。另外,请删除双引号。

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>