1

I have a simple jQuery script that I'm trying to build upon but I can't get the href string comparison to return true:

<a class="test" href="/Services/Cloud-Hosting">Click Me</a>​

My script is as follows:

$('.test').click(function() {
if ($(this).href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}
});​

I keep getting the alert of 'no' even thought the hrefs are the same. What am I missing?

Kyle Suss
  • 457
  • 3
  • 7
  • 18
  • Now after you got your answer, check this to know the explanation http://stackoverflow.com/questions/3722544/what-is-the-difference-between-this-and-this – Adi Jul 02 '12 at 18:17

4 Answers4

10

Change:

if ($(this).href

To:

if (this.href

Or $(this).attr('href') but former is better.

To read attributes, you need to use attr (shorthand for attribute)

This is what you should have:

if (this.href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}
Blaster
  • 9,414
  • 1
  • 29
  • 25
  • 5
    Be careful using `this.href`, in Chrome it returns the absolute path of the link (regardless of the `href` being a relative URL). [Demo](http://jsfiddle.net/QCx6D/). – David Thomas Jul 02 '12 at 18:19
  • @DavidsaysreinstateMonica that tip is so valuable, that I reckon it merits posting a new answer with that guidance so that researchers have an easier time understanding the difference. – mickmackusa Dec 08 '20 at 07:27
4

try this:

if ($(this).attr('href') == "/Services/Cloud-Hosting") {
Ram
  • 143,282
  • 16
  • 168
  • 197
1

See .attr() and try this:

$(this).attr('href') == "/Services/Cloud-Hosting"

instead

sinemetu1
  • 1,726
  • 1
  • 13
  • 24
Fydo
  • 1,396
  • 16
  • 29
1

jQuery objects don't have an href property. Just access the property of the HTMLAnchorElement using this.href instead of creating a new jQuery object with $(this).

Paul
  • 139,544
  • 27
  • 275
  • 264
  • 1
    As noted to another answer `this.href` isn't necessarily equal to `$(this).attr('href')`. [Demo](http://jsfiddle.net/QCx6D/). – David Thomas Jul 02 '12 at 18:20
  • @DavidThomas In that case wouldn't `this.getAttribute('href')` be the preferred way? – Paul Jul 02 '12 at 19:25