I need to move a parent anchor to wrap a child image more “closely”. A simplified version of my HTML is:
<a class="link">
<span class="container">
<img class="image" />
<span>An image caption.</span>
</span>
</a>
I’m looking for this result:
<span class="container">
<a class="link">
<img class="image" />
</a>
<span>An image caption.</span>
</span>
I tried:
/* I have to process each anchor individually and only make
* this move if there's a span.container as the first child.
*/
$('a.link').each(function() {
if ($(this).children('span.container').length > 0) {
$(this).find('img.image').wrap($(this));
$(this).children('span.container').unwrap();
}
});
I end up with:
<span class="container">
<a class="link">
<span class="container">
<img class="image">
<img class="image" />
</img>
<span>An image caption.</span>
</span>
</a>
<span>An image caption.</span>
</span>
Caveats: I’m n00b. I’m stuck with jQuery 1.3.2. I’m using an unwrap() plugin, which seems to be working as seen above. The problem is with my wrap($(this)) I think? $(this) should only contain <a class="link"> and not its children right? It seems to contain the children, they’re inserted in the wrap, and I get duplicate HTML. Many thanks in advance…
Fiddle