Crochers
Crochers

Reputation: 23

Event handling/Capturing

I want to attach an event listener purely in Javascript to "ul" html tag so that when I clicked on any "li" an alert will display the value of that corresponding "li":

<ul>
    <li>A<li/>
    <li>B<li/>
    <li>C<li/>
</ul>

If a clicked on A it should alert A , same for B and C

Upvotes: 2

Views: 49

Answers (4)

Md Rafee
Md Rafee

Reputation: 5530

You can select ul by getElementById and bind it to the event onclick. Check the JSFiddle

Upvotes: 0

StefanN
StefanN

Reputation: 911

document.querySelectorAll('li')
  .forEach(item =>
    item.addEventListener('click',
      () => alert('Item clicked')
    )
  );
li {
  cursor: pointer;
}

li:hover {
  background: lightgrey;
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

You have to loop through all <li/> elements inside the list and attach an eventListener to them.

See code example to find out how it works.

Upvotes: -1

Manikant Gautam
Manikant Gautam

Reputation: 3581

Get all li nodes and add click events on each nodes .

var lis =  document.getElementById("div").getElementsByTagName("li")
for(var i=0;i<lis.length;i++){
 lis[i].addEventListener('click', function(e){
      alert(e.target.textContent);
   })

}

// As if you want to have single click event on ul itself

document.getElementById("ul").addEventListener('click', function(e){
      alert(e.target.textContent);
   })
ul li {
  background: #cce5ff;
  margin: 5px;
  cursor:pointer;
}
<div id="div">
<ul >
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>
</div>

 <p> As if you want to have single click event on ul itself</p>
<hr>

<ul id="ul">
  <li>X</li>
  <li>Y</li>
  <li>Z</li>
</ul>

Upvotes: 1

nick zoum
nick zoum

Reputation: 7285

var list = document.querySelector("#list");
list.addEventListener("click", function(ev) {
  if (ev.target !== list) console.log(ev.target.textContent);
  // console is easier to test than alert(ev.target.textContent);
});
<ul id="list">
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>

Upvotes: 1

Related Questions