jquery - if href attr == ""

Phil picture Phil · Jul 1, 2011 · Viewed 19.8k times · Source

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!

Answer

T.J. Crowder picture T.J. Crowder · Jul 1, 2011

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