matt
matt

Reputation: 44293

jquery: Add class if link has a target blank?

hey guys, shouldn't that work?

//Add class if target blank
    $('.post .entry a').each(function() {
        if ( $(this).attr('target') == '_blank') ) {
            $(this).addClass('web');
        };
    });

anything wrong with this?

Upvotes: 2

Views: 8978

Answers (5)

Devner
Devner

Reputation: 7245

I found success with the following:

$('.post .entry a[href="_blank"]').addClass('web');

Upvotes: 0

Tomgrohl
Tomgrohl

Reputation: 1767

You have am extra ) on the if statement. Take that off an you'll be ok:

$('.post .entry a').each(function() {
    if ( $(this).attr('target') == '_blank' ) {
        $(this).addClass('web');
    };
});

A shorter way to do this would be:

$('.post .entry a[target="_blank"]').each(function() {
    $(this).addClass('web');
});

Uses less code too.

Actually @ariel's answer states a better way to do it.

Upvotes: 2

JohnP
JohnP

Reputation: 50019

You have an extra ). Just remove that and it's fine :)

$('.post .entry a').each(function() {
    if ( $(this).attr('target') == '_blank') ) {
---------------------------------------------^
        $(this).addClass('web');
    };
});

Upvotes: 7

ariel
ariel

Reputation: 16150

Please try

//Add class if target blank
$('.post .entry a[target="_blank"]').addClass('web');

Upvotes: 12

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

It's fine. But this should be inside a document.ready:

$(document).ready(function(){
   $('.post .entry a').each(function() {
        if ( $(this).attr('target') == '_blank') ) {
            $(this).addClass('web');
        };
    });
});

Hope this helps. Cheers

Upvotes: 2

Related Questions