How to appendTo closest div (by class)?
Asked Answered
D

1

6

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:

<div class="newsItem">
  <div class="newsHeader">
    <h2><a href="/news-information/67-latest-news-03.html">Latest News 03</a></h2>
  </div>
  <div class="newsIntro"><img src="/images/stories/opals-are-lucky/img_abopal_lucky.jpg" border="0" align="left" />Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce dictum sagittis sapien. Aliquam erat volutpat. Nulla facilisi. Ut purus neque, condimentum nec,
    auctor eget, semper ut, enim. Vestibulum sem tellus, vestibulum a, vehicula ut, feugiat id, libero. Pellentesque enim justo, condimentum sed, dictum at, viverra eget, odio. Aliquam feugiat metus id lacus. Cum sociis natoque penatibus et magnis dis
    parturient montes, nascetur ridiculus mus. Nam iaculis iaculis quam. Donec eu dui.</div>
  <div class="clear"></div>
</div>

<div class="newsItem">
  <div class="newsHeader">
    <h2><a href="/news-information/68-latest-news-03.html">Latest News 03</a></h2>
  </div>
  <div class="newsIntro"><img src="/images/stories/about-us/img_showroom.jpg" border="0" align="right" />Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce dictum sagittis sapien. Aliquam erat volutpat. Nulla facilisi. Ut purus neque, condimentum nec, auctor eget,
    semper ut, enim. Vestibulum sem tellus, vestibulum a, vehicula ut, feugiat id, libero. Pellentesque enim justo, condimentum sed, dictum at, viverra eget, odio. Aliquam feugiat metus id lacus. Cum sociis natoque penatibus et magnis dis parturient montes,
    nascetur ridiculus mus. Nam iaculis iaculis quam. Donec eu dui.</div>
  <div class="clear"></div>
</div>
Drollery answered 4/11, 2010 at 23:42 Comment(0)
L
13

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.

Lawford answered 4/11, 2010 at 23:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.