Consider the HTML
<ul>
<li>Default item</li>
<li>Default item</li>
</ul>
<button>Append</button>
and the jQuery code
$('button').live('click', function(){ //This action is done by an external script.
$('ul').append('<li>Added item</li>');
});
$('ul li').append('<b> x</b>'); // This action is done by me
The thing is, I need to append the “x” mark to all newly added elements to the dom.
In this case only default elements are appended with the “x” mark.
Newly added elements are not appended by “x”.
I am sure the work will be simple, but cant get it right !!
Live example – http://jsfiddle.net/vaakash/LxJ6f/1/
Your code is running right away, and so of course it only has access to the elements that already exist. The code adding new list items is running later, when the user clicks something. You’ll have to hook into that process as well.
One way is to hook the same event they are, and run your code from the event handler. Be sure to hook the event after they do.
Their code:
Your code (after theirs):
Updated fiddle
The reason I said your code needs to do its hookup after their code is that jQuery guarantees the order of the calls to event handlers: When the event occurs, the handlers are called in the order in which they were attached. By attaching your handler after they attach theirs, you guarantee that your handler is called after theirs has done its thing.
If you’re worried about the order getting mixed up, you could always delay your code slightly:
That way, your code is guaranteed to run after all of the event handlers hooked to the
clickhave been run.