Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can give the appended divs a class then call them by it like this :

$movies.append('<li class="movie" id="list"><a href="">'+ movie.name +'</a></li>');

//then later

let movies = $('.movie');
console.log(movies);

but if you meant to execute this script right after the ajax request then you should call a function in the ajax success since ajax is async and the moment you execute a jquery select , the elements are still not there because ajax takes more time to retrieve the data put it in the document... you can make a getMovies() to execute there like this:

//declare this outside the ajax

let movies = []

function getMovies(){
     return $('.movie');
}

then

//ajax
success: function(){
     movies = getMovies(); //add this line
}

there you go now you have movies stocked inside the 'movies' array

about 4 years ago · Juan Pablo Isaza Relatório

0

It seems you are running into a race condition of sorts. You are building the list using an asynchronous ajax request to an API. Before that completes, you are then attaching the Javascript code to trigger an event.

What you need to do is add the callback inside of the ready block after the list data is retrieved and the list is created.

about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda