0

Is it possible in JavaScript to have only one single listener for all <a> elements?

<ul>
    <li><a href="#1">1</a></li>
    <li><a href="#2">2</a></li>
    <li><a href="#3">3</a></li>
    <li><a href="#4">4</a></li>
    <li><a href="#5">5</a></li>
</ul>

That listener should take a value (e.g. #4) to update some div.

Alex
  • 1,781
  • 4
  • 25
  • 41

1 Answers1

1

I hope this piece of code helps you out, the listener attached on the ul tag is now catching all the click events on its children and parsing out their href values. You might want to use a jquery lib to further parse out the #hrefvalue.

  <ul>
<li><a href="#1">1</a></li>
<li><a href="#2">2</a></li>
<li><a href="#3">3</a></li>
<li><a href="#4">4</a></li>
<li><a href="#5">5</a></li>
</ul>
<script>
document.getElementsByTagName("ul")[0].addEventListener("click", function(e){
e.preventDefault();
alert(e.target.href);
});
</script>
Lakmal Caldera
  • 911
  • 1
  • 11
  • 23