1

I know that similar questions are being asked (like here) but, being a jQuery noob, I still can not attach a click listener to an a element within a li where the whole ul.li.a is dynamically appended to the DOM like this.

<div id="users-col">
  <!-- dynamically appended --> 
  <ul id="users-list">
       <li>
          <a class="user" id="Alice">Alice</a>
       </li>
       <li>
          <a class="user" id="Bob">Bob</a>
       </li>
  </ul>
   <!-- END dynamically appended --> 
</div>

Here is a (one of the many) jQuery functions that I have tried:

$('#users-col ul.li.a').on('click', '.user', (function () {
  console.log('user clicked:', this.id); 
});

How can I fix this?

3
  • 1
    li and a are not classes, so they shouldn't have . in front of them if you're trying to select them. Separate elements with > to indicate parent - child relationship. Commented Jun 6, 2018 at 6:15
  • Well, I also tried $("#users-col ul > li > a") but failed. Commented Jun 6, 2018 at 6:17
  • 1
    @Karlom $("#users-col ul > li > a") will not work since your ul li and a are dynamically created. Commented Jun 6, 2018 at 6:18

3 Answers 3

5

You need to bind the event on element that is available (not added dynamically)

$('#users-col').on('click', 'a.user', (function () {
  console.log('user clicked:', this.id); 
});

For reference, jQuery.on

Sign up to request clarification or add additional context in comments.

Comments

0

in such case you must hook an event with parent of dynamically created children:

$('#users-col').on('click', 'a.user',        (function () { 
console.log('click bound'); 
});

Comments

0

For convenience sake and reuse, I leave the first field just directly tied to the document:

$(document).on('click', '.user', (function () {
  console.log('user clicked:', this.id);
}));
<div id="users-col">
    <!-- dynamically appended -->
    <ul id="users-list">
        <li>
            <a class="user" id="Alice">Alice</a>
        </li>
        <li>
            <a class="user" id="Bob">Bob</a>
        </li>
    </ul>
    <!-- END dynamically appended -->
</div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>

The listener is directly tied to the document vice the class, so now it is very easy to reuse this class dynamically across your entire document.

2 Comments

I had try this. Its problem was that it was triggered for whatever click on the page.
@Karlom no, it should only trigger for tags with class="user". Unless your body contains class user, it shouldn't trigger for every click.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.