0

In my markup, my A element has a href equal to "": <a href="">. When trying to display it though using an like for example alert(jQuery('#my_href_link').attr('href')), it returns "undefined" rather than an empty chain or something.

So the solutions I found everywhere:

if (jQuery('#my_href_link').attr('href') == '') 

or

if (jQuery('#my_href_link').attr('href').length == 0)

... don't work.

Yet they seem to work for everybody except me. Why is that?

Markup:

<a id="my_href_link" href="">
    <img src="image.jpg">
</a>
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
drake035
  • 3,955
  • 41
  • 119
  • 229

1 Answers1

6

Take advantage of the truthy and falsey nature of Javascript variables. In this if statement an empty string or undefined will cause the conditional to evaluate to false.

if (jQuery('#my_href_link').attr('href'))

You can easily negate this statement using ! since the following == true:

alert(!undefined);
alert(!"");

Read more about truthy and falsey

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Ok, I would like to made the opposite statement. Can I write the same thing with a "!" right before "jQuery"? I just tried and it seems to detroy my code execution. – drake035 Oct 24 '13 at 12:04
  • The `!` should work. How does it destroy your code execution can you provide an example? – Kevin Bowersox Oct 24 '13 at 12:07
  • My page's JS code is very complicated so there must be some intricate conflict somewhere. I'll deal with that, thanks anyway. – drake035 Oct 24 '13 at 12:21
  • 1
    @drake035 Make sure your using a good editor that will highlight syntax errors such as Aptana. You can also run your js through jsonlint which will help detect syntax errors. – Kevin Bowersox Oct 24 '13 at 12:23