Phil
Phil

Reputation: 51

jquery - if href attr == ""

I am trying to find out if a href attr is empty do something, my code is as follows...

jQuery('#sidebar a').click(function() {

     var bob = jQuery(this).attr("href");

     if(jQuery(bob).attr() == "") {
            alert('I am empty href value');
        }

    });

I am not sure where I am going wrong? Any advice? Thanks!

Upvotes: 5

Views: 21536

Answers (6)

MAK Ripon
MAK Ripon

Reputation: 1081

Answer is already given by great guys.

just check if(bob=="")

I would add one more line. Just for safety you can trim bob using jQuery.

bob = jQuery.trim(bob);

This will make the validity a bit stronger.

Upvotes: 2

Michael Irigoyen
Michael Irigoyen

Reputation: 22957

You are setting a variable and then never checking it. Personally, I wouldn't even create a variable; Just do the check.

jQuery('#sidebar a').click(function() {
    if(jQuery(this).attr("href") == "") {
        alert('I am empty href value');
    }
});

Upvotes: 3

Nishchay Sharma
Nishchay Sharma

Reputation: 1324

jQuery('#sidebar a').click(function() {

     if(jQuery(this).attr("href")==""){
            alert('I am empty href value');
        }

    });

There is no use of filtering your bob again with jQuery. :)

Upvotes: 1

bingjie2680
bingjie2680

Reputation: 7773

use this instead

jQuery('#sidebar a').click(function() {

 var bob = jQuery(this).attr("href");

 if(bob === "") {
        alert('I am empty href value');
    }

});

Upvotes: 2

Niklas
Niklas

Reputation: 30012

You are defining the attribute href to variable bob already. Just use:

bob == ""

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075597

You're passing bob into jQuery as a selector. Just test it directly:

jQuery('#sidebar a').click(function() {

    var bob = jQuery(this).attr("href");

    if (bob == "") {
        alert('I am empty href value');
    }

});

Or better yet, just:

    if (!bob) {

Gratuitous live example

Upvotes: 8

Related Questions