John
John

Reputation: 291

Wrap <img> with a <div>, but if <img> has parent and is <a>, wrap anchor instead

When wordpress adds an image to the post it wraps it up in an anchor tag. Like this:

<a href="link"><img src="image" /></a>

I would like to wrap the anchor with a div and add an overlay span after the image. Like this:

<div class="imagewrap">
   <a href="">
     <img src="image" />
     <span class="overlay"></span>
   </a>
</div>

The following code does just that.

$('#post a').has('img').wrap('<div class="imagewrap" />').find('img').after('<div class="overlay"></div>');

However, when you add a linked image to a wordpress post it doesn't wrap the image in anchor tags and thus doesn't work. If there are no anchor tags, the image tag should be wrapped instead. Like this:

<div class="imagewrap">
     <img src="image" />
     <span class="overlay"></span>
</div>

Targeting the img tag is of course possible, but if so, the instances where the img tag has an anchor parent, the anchor doesn't get wrapped by the div. Any idea how to wrap the anchor if it has an img inside it, and if it doesn't it should just wrap the img tag instead?

Thanks in advance.

Upvotes: 1

Views: 1242

Answers (2)

adeneo
adeneo

Reputation: 318302

Something like this should work:

​$('#post img')​.each(function() {
    if ($(this).parent().is('a')) {
        $(this).parent('a')
               .wrap('<div class="imagewrap" />');
    }else{
        $(this).wrap('<div class="imagewrap" />');
    }
    $(this).after('<div class="overlay"></div>');
}​);​

Iterates over all the images, and wraps the parent <a> element if it has one, otherwise it wraps the image element, an adds the overlay after the <img> tag in both instances.

Or if you prefer to wrap it in one statement:

$('#post img').map(function() {
        return $(this).parent('a').length?$(this).parent('a'):$(this);
    }).wrap('<div class="imagewrap" />').end()
      .after('<div class="overlay"></div>')

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71939

This is ugly but it should work as your second selector:

$('img:not(a img)');

Upvotes: 1

Related Questions