Scott
Scott

Reputation: 675

Can't loop through elements created by jquery

I've added a bunch of links to a div like this:

$('#links').append('<a href="http://example.com/">Example</a>');

But when I try to loop through them with $('#links a').each it only finds the links that are already there in the HTML.

What am I doing wrong?

Upvotes: 1

Views: 245

Answers (3)

naugtur
naugtur

Reputation: 16905

This should work. It wouldn't work if You did something more like that:

$('#links').append('<a href="http://example.com/">Example</a>').find('a').each();

or fetching $('#links a') before You do the appending

Upvotes: 0

Gabriel Hurley
Gabriel Hurley

Reputation: 40082

Your code as you've given it above works fine (tested). That means you're doing something else that's causing the problem. Possibilities include:

  • Using the wrong selector.
  • Appending the elements in the wrong place.
  • Storing the value of your selector in a variable and not updating it after the new elements are appended.

My personal guess is the last one there, since it's the least obvious. But I've made all three mistakes in the past. Hope that helps.

Upvotes: 4

cherouvim
cherouvim

Reputation: 31928

That is strange, but try viewing the DOM as it is after the manipulation in case the end HTML is not as you expect it to be. You can do this via web developer toolbar (view generated source) or via firebug.

Upvotes: 0

Related Questions