3

Possible Duplicate:
this.href vs $(this).attr('href')

Here is my code:

 $(function () {
        $("a.Delete").click(function () {
            console.log(this.href);
            console.log($(this).attr("href"));
            return false;
        });

and here is my link

<a class="Delete" href="/Contact/Delete/10402">Delete</a>

Here is my output:

http://localhost:59485/Contact/Delete/10402
/Contact/Delete/10402

Why the difference doesn't the attr method just get the attribute. Isn't that what this.href does? Is the href property special in some way that it actually gives you the absolute url?

Community
  • 1
  • 1
ek_ny
  • 10,153
  • 6
  • 47
  • 60

3 Answers3

6

HTML a elements have an href property that acts similarly to the document.location object. It will return the fully qualified URL of the href specified in the [href] attribute. Including the protocol, domain, etc.

jQuery's attr method gets the attribute value as-is. Behind-the-scenes it uses getAttribute (or equivalent).

If you wanted to get the literal attribute value in raw JS you'd use:

anchor.getAttribute('href');

If you wanted to get the fully qualified URL in jQuery you'd use:

$('a').prop('href'); //jQuery 1.6+
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
5

The first version, this.href is reading the attribute directly from the javascript implementation the browser uses. This is providing you with an absolute URL as the browser is interpreting the href attribute and combining it with the current host URL.

The second, $(this).attr("href") is wrapping the element in a jQuery object, and then accessing the href attribute of the object. There is no processing on the value being returned so it is simply giving you the exact string which was in your HTML.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2

this.href gives you the absolute URI.

$(this).attr("href") gives you whatever text is in the href attribute which may or may not be a relative URI.

Tim Rogers
  • 21,297
  • 6
  • 52
  • 68