How to appendTo closest div (by class)?

SoulieBaby picture SoulieBaby · Nov 5, 2010 · Viewed 10.3k times · Source

I'm trying to do some jQuery which will find images inside text, wrap the image inside a div and then move it to another div, yet I can't seem to get it working.

Here's the code that I have so far which works:

$(".newsIntro").find("img").wrap("<div class=\"newsImage\" />");

But, when I try to move it, either all images on the page move inside the one div (instead of moving to their parent div (".newsItem"), or nothing happens.

$(".newsImage").appendTo( $(this).closest(".newsItem") );

The above doesn't do anything:

$(".newsImage").appendTo(".newsItem");

The one above that moves them all into the first .newsItem div.

Here's a snippet of the HTML:

Answer

Nick Craver picture Nick Craver · Nov 5, 2010

You need to loop through using .each() so this refers to each element as you go, like this:

$(".newsImage").each(function() {
  $(this).closest(".newsItem").append(this);
});

Since .appendTo() gets flipped around to .append() anyway, it's more efficient to go this route.