<ul>
<li>Hello..</li>
</ul>
$('input').click(function(){
$('ul').prepend($('<li>Another Hello...</li>').click()); // not working [1]
$('ul').prepend('<li>This is hello appending...</li>').children(':first').click(); // this is working [2]
});
$('ul li').live('click', function(){
console.log('New li clicked...');
});
Why the [1] code snippet working? Is there any other ways to resolve this the same task? I want to fire the click event at the time of prepend().
N.B: here prependTo() can be used, but is it possible do the same job using prepend().
Because the new element,
$('<li>Another Hello...</li>'), is not part of the DOM tree (the document) yet, so the event cannot bubble up to fire the event handler bound with.live()..live()binds the event handler to the document root and works because events are bubbling up the DOM tree. That means, first the event handler of the element where the event originated is called, then the event handler of its parent and so on, for every ancestor, until it reaches the document root.But if the element is not added to the document, it has not parent node, so the event cannot bubble up.
You could use
.prependTo()[docs] instead: