0

I'm having some issues with this code. I'm trying to dynamically create images as unordered list items that can be clicked and repeat the process. However, when I get to the second level, I'm not able to click on the images to get them to generate additional list items underneath. Can someone tell me what I'm doing wrong here? I'm able to click on any one of the first three images (all with the same class) and it works; I'm not sure why the second tier wouldn't work.

$(".pic").on('click',function() {
var parent = $(this).parent().append("<ul><li class='child'><img src='http://www.clipartbest.com/cliparts/9Tp/MAz/9TpMAzbTE.png'/></li></ul>");
});

$(".child").on('click',function() {
alert($(this).parent().attr('class'));
var parent = $(this).parent().append("<ul><li class='child'><img src='http://www.clipartbest.com/cliparts/9Tp/MAz/9TpMAzbTE.png'/></li></ul>");
});
zklim
  • 525
  • 1
  • 5
  • 9

1 Answers1

2

Whenever you create an element dynamically, you have to reference it first through the document, or otherwise through a parent that exists on page load. This is because the DOM is already loaded by the time dynamic elements are created, so the click functions are not binded to those. Binding to the document, for example, always circumvents this problem.

Try changing the listeners to:

$(document).on('click', '.pic', function() {
var parent = $(this).parent().append("<ul><li class='child'><img src='http://www.clipartbest.com/cliparts/9Tp/MAz/9TpMAzbTE.png'/></li></ul>");
});

$(document).on('click', '.child', function() {
alert($(this).parent().attr('class'));
var parent = $(this).parent().append("<ul><li class='child'><img src='http://www.clipartbest.com/cliparts/9Tp/MAz/9TpMAzbTE.png'/></li></ul>");
});
ajdhefley
  • 146
  • 5