2

I have images on my website, some have the target="_blank" attribute and some not.

here are 2 examples :

with target=_blank :

<a href="/mission.jpg" target="_blank"><img class="alignnone size-medium wp-image-1270" src="/mission-300x289.jpg" alt="mission" width="300" height="289" /></a>

without target=_blank :

<a href="/mission_1.jpg"><img class="alignnone size-medium wp-image-1271" src="/mission-300x289.jpg" alt="mission_1" width="300" height="289" /></a>

I'm using this code to remove the links from my images :

$("a:has(img)").each(function() { $(this).replaceWith($(this).children()); })

no I would like to add a condition to remove the link only if the image has not target=_blank attribute.

can anybody helpe me with this ?

thanks a lot for your help;

mmdwc
  • 1,095
  • 6
  • 27
  • 53

5 Answers5

2

Try

$("a:not([target='_blank']) img").unwrap();

OR

$("a[target !='_blank'] img").unwrap();

Fiddle

Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
1

Use this:

     $('a:not([target="_blank"]):has(img)').each(function() { 
         $(this).replaceWith($(this).children()); 
    })

working fiddle

Nahum
  • 101
  • 6
0
  $("a:has(img)").each(function() { 
    var x=$(this).attr('target');

    if(x!="_blank"){
      //do your stuff here
    $(this).remove();
    $(this).replaceWith($(this).children()); 
    }
})

JSFIDDLE DEMO

Vaibs_Cool
  • 6,126
  • 5
  • 28
  • 61
0

You can use

$("a[target!='_blank']:has(img)").each(function() {
  $(this).replaceWith($(this).children());
})

See jsfiddle.

Marvin
  • 13,325
  • 3
  • 51
  • 57
0

This is another way, specifically to check against multiple browsers in relation to this question.

jQuery hasAttr checking to see if there is an attribute on an element

$('a:has(img)').each(function() {
    if (!!$(this).attr('target')) {
        (this).unwrap();
    }
});
Community
  • 1
  • 1
Chris Hawkes
  • 11,923
  • 6
  • 58
  • 68