Ilya Ilya - 3 months ago 8
jQuery Question

Calling li from dynamically generated div

I have a div and then dynamically generating several divs within, so it looks somethings like this generated:

<div class="info">
<div class="other"></div>
<div class="items">
<li></li>
<li></li>
</div>
</div>


I'm using
.append
on
$(".info")
to insert both the div's and li's (in one of them). My problem is to make li's clickable. As they are dynamically generated (as well as their parent
$(".items")
), this doesn't work:

$(".items").on('click', 'li', function() {
console.log("val");
});


Edit: Hey, I've changed div to ul, so it's generated:

<div class="info">
<div class="other"></div>
<ul class="items">
<li></li>
<li></li>
</div>
</div>


However, my previous js still doesn't work. Trying now all your suggestions! Thanks!

Answer

You have to put the event delegation to .info, body or document, because you even generate .items dynamically. And li is only valid inside an ul.

$(".info").on('click', '.items li', function(e) {
    console.log("val"); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="info">
  <div class="other"></div>
  <ul class="items">
    <li>one</li>
    <li>two</li>
  </ul>
</div>

Comments