Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  77] [ 2]  / answers: 1 / hits: 46360  / 13 Years ago, sun, december 4, 2011, 12:00:00

Consider the HTML

<li>Default item</li>
<li>Default item</li>

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 -

More From » jquery


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:

$('button').live('click', function(){
$('ul').append('<li>Added item</li>');

Your code (after theirs):

$('button').live('click', markButtons);


function markButtons() {
$('ul li:not(.marked)')
.append('<b> x</b>');

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:

$('button').live('click', function() {
setTimeout(markButtons, 0);

That way, your code is guaranteed to run after all of the event handlers hooked to the click have been run.

[#88760] Friday, December 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago