remove img link if not target=blank

443 views Asked by At

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;

5

There are 5 answers

0
Sudharsan S On

Try

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

OR

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

Fiddle

0
Vaibs_Cool On
  $("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

0
Nahum On

Use this:

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

working fiddle

0
Marvin On

You can use

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

See jsfiddle.

0
Chris Hawkes On

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();
    }
});