9

Possible Duplicate:
How to get “raw” href contents in JavaScript

Sometimes you write in your code relative paths to your files, so in the code the href attribute value could be somefile.php yet when clicking of course the anchor would send you to http://www.yourdomain.com/somefiles.php

Now my question is could I somehow obtain the full href of an anchor?

When using $(anchor).attr("href") you only get the relative path.

Community
  • 1
  • 1
eric.itzhak
  • 15,752
  • 26
  • 89
  • 142

3 Answers3

20

You can use .prop:

$(anchor).prop("href")

Here's an example:

console.log($("a").prop("href")); //http://fiddle.jshell.net/_display/sth
console.log($("a").attr("href")); //sth
Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78
15

element.href will get the entire href

FIDDLE

EDIT:

I'll quote something from jQuery's website here:

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

Since .attr() gets the actual value typed in the attribute, as it probably used the native getAttribute(), the proper way to do this would be to get the native javascript element, and then use the native element.href which will get the href including the domain and pathname etc.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • But i'm not trying to get the attribute from within the event. – eric.itzhak Nov 19 '12 at 15:21
  • `document.getElementById('elementID').href` or `$(anchor)[0].href` will do that, as all you need is the plain JS object, not the jQuery object. – adeneo Nov 19 '12 at 15:22
  • Oh i get it now. thanks i guess i've became too dependant on jQuery. – eric.itzhak Nov 19 '12 at 15:23
  • @eric.itzhak That's why it's a duplicate. Your asking for a jquery solution when plain javascript works just fine – Mike B Nov 19 '12 at 15:24
  • Not only that, but `href` is an attribute not a property, so the `prop()` method is'nt really intended to be used that way -> [**link**](http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/), even if it works as of now there is no guarantee that prop() will continue to work with the href **attribute**! – adeneo Nov 19 '12 at 15:26
  • Here is a fiddle I needed to make to convince myself about all this: http://jsfiddle.net/mplungjan/J9bWf/show – mplungjan Nov 19 '12 at 15:38
0

you can use jQuery prop function.

for testing try following codes in your console for this page;

$("a:eq(6)").prop("href")
$("a:eq(6)").attr("href")

and for more information you can search for html attribute and property.

Onur Topal
  • 3,042
  • 1
  • 24
  • 41