无法读取属性' innerText'未定义的

时间:2018-01-03 15:38:38

标签: javascript jquery html dom

我在使用以下代码时遇到错误。如果选择了元素,我会尝试获取id id05的值(选择的类是选中的元素)。

HTML:

<ul id="items" class="clearfix">

  <!-- ---------- this item is selected --------------- -->
  <li class="item folder selected">
    <a href="/t1/">

      <!-- -------this is the element whose innerTEXT i want ----------- -->
      <span id="id05" class="label" title="t1">t1</span>
    </a>
  </li>


  <!-- ---------- this item is also selected --------------- -->

  <li class="item folder page selected">
    <a href="/upl/" target="_blank">

      <!-- -------this is the element whose innerTEXT i want ----------- -->
      <span id="id05" class="label" title="upl">upl</span>
    </a>
  </li>

  <!-- ---------- this item is not selected --------------- -->

  <li class="item file">
    <a href="Ff.html/" target="_blank">
      <span id="id05" class="label" title="Ff.html">Ff.html</span>
    </a>
  </li>
</ul>

JS:

function del() {
  var name;

  var nam = document.querySelectorAll(".selected");

  for (var i = 0; i < nam.length; i++) {
    name = document.getElementById("id05")[i].innerText; //Here is the error
  }
  console.log(name);
}
  

console.log - 未捕获的TypeError:无法读取属性&#39; innerText&#39;未定义的

1 个答案:

答案 0 :(得分:3)

请改为尝试:

HTML:

<ul id="items" class="clearfix">
  <li class="item folder selected">
    <a href="/t1/">
      <span class="label" title="t1">t1</span>
    </a>
  </li>
  <li class="item folder page selected">
    <a href="/upl/" target="_blank">
      <span class="label" title="upl">upl</span>
    </a>
  </li>
  <li class="item file">
    <a href="Ff.html/" target="_blank">
      <span class="label" title="Ff.html">Ff.html</span>
    </a>
  </li>
</ul>

使用Javascript:

function del(){
  var selected = document.querySelectorAll("li.selected span");
  selected.forEach(item => {
    console.log(item.innerText);
    // Do what you need to each item here
  });
}

我刚删除了id,并在查询选择器中定位了子跨度。