Jquery - if href attr == ""

I am trying to find out if href attr is empty to 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'm not sure where I am wrong? Any advice? Thanks!

+4
source share
6 answers

You pass bob to jQuery as a selector. Just check it out directly:

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

Or better yet, simply:

  if (!bob) { 

Win-win live example

+8
source

use this instead

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

The answer is already given by the great guys.

just check if (bob == "")

I would add another line. Just for security, you can crop bob with jQuery.

 bob = jQuery.trim(bob); 

This will make the action stronger.

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

No need to filter your bob again using jQuery. :)

+1
source

You set a variable and then do not check it. Personally, I would not even create a variable; Just check.

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

You have already defined the href attribute for the bob variable. Just use:

 bob == "" 
0
source

All Articles