Snorlax Snorlax - 2 months ago 8
CSS Question

Javascript: Selecting List from UL



var ul = document.getElementById("parent-list");
document.querySelectorAll("#parent-list li").onclick = function() {

alert('click!');

}

<ul id="parent-list">
<li id="item-1">Item 1</li>
<li id="item-2">Item 2</li>
<li id="item-3">Item 3</li>
<li id="item-4">Item 4</li>
<li id="item-5">Item 5</li>
<li id="item-6">Item 6</li>
<li id="item-7">Item 7</li>
<li id="item-8">Item 8</li>
<li id="item-9">Item 9</li>
</ul>





I'm trying to have an alert popup of the item clicked when I click on a "li" element with javascript only. I know how to do in jquery but I can't figure out how to do it with javascript.

fiddle: https://jsfiddle.net/7jcksznz/1/

Answer

querySelectorAll returns an HTML collection. You would need to attach the event to each one. You would need to loop over the collection.

var lis = document.querySelectorAll("#test li");
for (var i = 0; i < lis.length; i++) {
  lis[i].addEventListener("click", function() {
    console.log(this.innerHTML);
  });
}
<ul id="test">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

A better option is to add one click on the UL and use the event to determine which li was clicked.

document.getElementById("test").addEventListener("click", function(event) {
  var li = event.target;
  console.log(li.innerHTML);
});
<ul id="test">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Comments