listener on UL iterate through li

Viewed 30

I have the following html:

<ul class="collection">
   <li>a
      <a class=" delete-item secondary-content">
         <i class="fa fa-remove"></i>
      </a>
   </li>
   <li>s
      <a class=" delete-item secondary-content">
         <i class="fa fa-remove"></i>
      </a>
   </li>
   <li>w
      <a class=" delete-item secondary-content">
         <i class="fa fa-remove"></i>
      </a>
   </li>
</ul>

I have an onclick listener on the UL (called taskList). console.log says the element UL (taskList) is an object. Can I iterate through the li's as follows:

for (const task in taskList) {
   console.log(task);
}
1 Answers

No, for ... in will loop over the properties of the object. You could use for ... of to loop over the children.

const taskList = document.querySelector('ul.collection');
for (const task of taskList.children) {
   console.log(task.outerHTML);
}
<ul class="collection">
   <li>a
      <a class=" delete-item secondary-content">
         <i class="fa fa-remove"></i>
      </a>
   </li>
   <li>s
      <a class=" delete-item secondary-content">
         <i class="fa fa-remove"></i>
      </a>
   </li>
   <li>w
      <a class=" delete-item secondary-content">
         <i class="fa fa-remove"></i>
      </a>
   </li>
</ul>

Related