Asfan Ulla
Asfan Ulla

Reputation: 49

Cannot read property 'innerText' of undefined

I am having errors with the following code. I am trying to get the values of id id05 if the elements are selected (class selected are the elements selected).

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 - Uncaught TypeError: Cannot read property 'innerText' of undefined

Upvotes: 0

Views: 15099

Answers (1)

Rick
Rick

Reputation: 997

Try this instead:

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
  });
}

I just removed the id's and targeted the child span in the query selector.

Upvotes: 4

Related Questions