Prabhu
Prabhu

Reputation: 13335

How to reference a bunch of just-added list items in jQuery?

How do you get a reference to a bunch of li's that were just appended to a ul

Say I have a list:

<ul id="mylist">
  <li>1</li>
  <li>2</li>
</ul>

Now I'm appending several more li's to the above ul, so:

$('mylist').append(response);

response looks like this:

"<li>3</li>
 <li>4</li>
 <li>5</li>"

I want to attach a click handler to the newly appended li's, but how do I get a reference those li's?

UPDATE: ul#mylist is within a popup and is not initially visible, and this popup is shown when another button is clicked:

$mybtn.click(function(){
  $('#mylist').show();
});

So, where would I define the "on" handler? if I do it within he button click handler, then it will attach the "on" handler multiple times, right, each time the button is clicked? I can't also define the "on" handler on page load, because mylist is not visible then.

Upvotes: 1

Views: 49

Answers (3)

Rastko
Rastko

Reputation: 468

If you want to access strictly last added elements, you can traverse it in multiple ways:

You can go $("ul#mylist li:last-child"), or $("ul#mylist li:nth-child(n)") or edit them, adding them a class before appending, so you can mark them visually as last addition.

Upvotes: 0

xat
xat

Reputation: 346

try

$('#mylist').on('click', 'li', function() { console.log('whatever'); });

Upvotes: 2

the system
the system

Reputation: 9336

Create the elements before you append them.

var els = $(response).appendTo('#mylist')
                     .on("click", function() { /* your code */ });

Or if it's only for the handler, you could just have a delegate handler on your ul, and not worry about it.

// on page load
$('#mylist').on("click", "li", function() { /* your code */ });

// on response
$('#mylist').append(response);

Upvotes: 4

Related Questions