Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I access the list element that is appended after html was created

I am adding a list element using the append function in jQuery, how do I reference this on my onclick function? Below is my code

$(function() {

  let $movies = $('#showList')
  let $m = $('#show')
  $.ajax({
    method: 'GET',
    url: 'http://api.tvmaze.com/shows',
    success: function(movies) {
      $.each(movies, function(i, movie) {
        $movies.append('<li id="list"><a href="">' + movie.name + '</a></li>')
      })
    }

  })

});

$('#list').on('click', 'a', function(event) {
  console.log('here');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<h1 id='bruh'>TV Shows</h1>
<ul id="showList"></ul>
<div id="show"></div>
<form id="searchForm">
  <input type="text" id="search_term">
  <label for="text">Search</label>
  <button>Submit</button>
</form>
<a id="homelink" href="#" hidden>Back to All Shows</a>

There is no message in console when I click on the link.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The attribute id should unique in a document, you can use class instead.

Try $('body').on('click', '.list a', function(event){....

Demo:

$(function() {

  let $movies = $('#showList')
  let $m = $('#show')
  $.ajax({
    method: 'GET',
    url: 'http://api.tvmaze.com/shows',
    success: function(movies) {
      $.each(movies, function(i, movie) {
        $movies.append('<li class="list"><a href="">' + movie.name + '</a></li>')
      })
    }

  })

});

$('body').on('click', '.list a', function(event) {
  console.log('here');
  event.preventDefault();//stay on the same page
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<h1 id='bruh'>TV Shows</h1>
<ul id="showList"></ul>
<div id="show"></div>
<form id="searchForm">
  <input type="text" id="search_term">
  <label for="text">Search</label>
  <button>Submit</button>
</form>
<a id="homelink" href="#" hidden>Back to All Shows</a>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading