Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Json and DOM traversing. Problems

I am solving some challenge, a kind of app where I can order pizza online. So, I added my pizza list with a json file (that is ok), and I want to choose the pizza i click and to add it to another list.

$("#pizzaList li").each(function() {
  $(this).on("click", function () {
  console.log( $(this).text() );
} ); });

I have discovered, when I add pizza list with JSON I cannot traverse List Items with DOM.

$.getJSON('pizzas.json', function (data) {
    var pizzaHTML = '<h3 class="pizzaTitle">Pizza Menu: </h3>'
        pizzaHTML +=  '<ul id="pizzaList">';

    $.each(data,function (index, pizza) {

      pizzaHTML += '<li>' + pizza.name +" "+ pizza.currency + pizza.price +'</li>';
    });
    pizzaHTML += '</ul>';
    $('#pizzaMenu').html(pizzaHTML)
  }).fail(function(jqHXR){
    alert(jqHXR.statusText)}); 

But when I add directly my pizza List to HTML (without DOM) I easily can select List Items.

<ul>
<li>Margarita</li>
<li>Napolitana</li>
<li>Di Mari</li>
</ul>

my question is, how can i select List Items, when its elements are added with json file?

2 Answers

Steven Parker
Steven Parker
243,658 Points

It might just be a timing issue. If you set the event handlers when the program first loads, it would work for items in the HTML, but the dynamically added ones would not be there yet. For those, you'd need to defer establishing the handlers until after the elements or added.

Alternatively, you could establish delegated handlers which would work on items added later.

that is my solution.

$("#pizzaMenu").on("click", 'li', function (){

  console.log( $(this).text() );
 }); 

Thanks! I will try it in my next programming session and i will write you.