为什么我无法从LI获取DIV子元素?

问题描述 投票:0回答:1

为什么代码总是返回 false? 为什么我无法从 LI 获取 DIV 子元素?

let li = document.getElementById('ul').children
console.log(li)
for(i=0;i<li.length;i++)
  li.hasChildren ? console.log("true") : console.log("false")// only false
<div id="conteinerTask2">
    <ul id="ul">
        <li class= "el">Element 1
            <div class="el-txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem eum quibusdam obcaecati sunt nulla, culpa nesciunt quas in officia sit. Illo aliquam beatae amet eos placeat neque, earum officiis ratione reiciendis exercitationem.</div></li>
        <li class= "el">Element 2
            <div class="el-txt">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Accusamus ex commodi, laudantium corrupti nam quos.</div></li>
        <li class= "el">Element 3
            <div class="el-txt">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ipsa obcaecati delectus nulla aperiam sint sit aliquam natus! Voluptatum, minima libero.</div></li>
        <li class= "el">Element 4
            <div class="el-txt">Lorem ipsum, dolor sit amet consectetur adipisicing.</div>
        </li>
    </ul>
</div>

javascript dom
1个回答
0
投票

首先,在

for
循环中,您仅访问 li 元素的
集合
,而不是单独访问每个
li
,因为您不通过索引访问它们。

其次,没有

hasChildren
属性。您可以使用
children.length > 0
来代替。

let li = document.getElementById('ul').children

for (i = 0; i < li.length; i++) {
  li[i].children.length > 0 ? console.log("true") : console.log("false") // only false
}
<div id="conteinerTask2">
  <ul id="ul">
    <li class="el">Element 1
      <div class="el-txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem eum quibusdam obcaecati sunt nulla, culpa nesciunt quas in officia sit. Illo aliquam beatae amet eos placeat neque, earum officiis ratione reiciendis exercitationem.</div>
    </li>
    <li class="el">Element 2
      <div class="el-txt">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Accusamus ex commodi, laudantium corrupti nam quos.</div>
    </li>
    <li class="el">Element 3
      <div class="el-txt">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ipsa obcaecati delectus nulla aperiam sint sit aliquam natus! Voluptatum, minima libero.</div>
    </li>
    <li class="el">Element 4
      <div class="el-txt">Lorem ipsum, dolor sit amet consectetur adipisicing.</div>
    </li>
  </ul>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.