Ben Iskander
Ben Iskander

Reputation: 616

jQuery add class when link does not contain an image

I'm trying to get jQuery to add a class to all external links, but only when the link is wrapped around text and not an image. I've used the :not selector and the code looks right to me but for some reason it's having the opposite effect and adding the class to images and not the text links.

Any ideas what I'm doing wrong?

Thanks, here's my code…

jQuery( document ).ready(function($) {
    // Add a css class to all external text links
    $('#main a:not(:has(img)').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).addClass("externalLink");
});

Upvotes: 1

Views: 339

Answers (3)

Iago
Iago

Reputation: 1214

LIVE DEMO: http://jsfiddle.net/don/0h56bjae/4/


You can use each() to check if the link has image and add class if yes. And use RegExp to check if the url is external or not.

var cp = new RegExp(location.host);

$('a').each(function() {
    if($(this).find("img").length > 0 && cp.test($(this).find('img').attr('src')) == false) {
        $(this).addClass('external-img');
    }
});

Upvotes: -1

xec
xec

Reputation: 18024

It seems you're missing a closing ) in the selector, and the order of the nested pseudo-selectors matter, try reversing them: :not(:has(img)) as opposed to :has(:not(img))

The amended code then looks like:

jQuery( document ).ready(function($) {
    // Add a css class to all external text links
    $('#main a:not(:has(img))').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).addClass("externalLink");
});

http://jsfiddle.net/y5e8kxz5/

Upvotes: 2

wiesion
wiesion

Reputation: 2455

I think you made a syntax error (not parentheses are opening but not closing), and as far as i know you don't need to surround :has(img) with parentheses.

jQuery( document ).ready(function($) {
    // Add a css class to all external text links
    $('#main a:not:has(img)').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).addClass("externalLink");
});

Upvotes: 1

Related Questions