Get local href value from binding (a)

I have an anchor tag with a local href value and a JavaScript function that uses the href value, but directs it to a slightly different place than usual. Tag looks like

<a onclick="return follow(this);" href="sec/IF00.html"></a> 

and a JavaScript function that looks like

 baseURL = 'http://www.someotherdomain.com/'; function follow(item) { location.href = baseURL + item.href; } 

I would expect that item.href would just return a short string of "sec / IF00.html", but instead it returns the full href, "http://www.thecurrentdomain.com/sec/IF00.html". Is there a way that I can pull out just the short href as put in the anchor <a> tag? Or do I lose that by natural HTML behavior?

I suppose I could use a string manipulation to do this, but it gets tricky because my local page may actually be "http://www.thecurrentdomain.com/somedir/somepath/sec/IF00.html", and my href field may or may not have a subdirectory in it (for ex href="page.html" vs. href="sub/page.html" ), so I cannot always just remove every thing before the last slash.

You may wonder why I'm asking about this, and that is because it will just make the page a lot cleaner. If it is not possible to get only a short href (as indicated in the anchor <a> ), then I could probably just insert an extra field in the tag, for example link="sec/IF00.html" , but again, that would be a bit dirtier.

+46
javascript html href
Mar 15 '13 at 18:39
source share
5 answers

The following code gets the full path where the anchor points are:

 document.getElementById("aaa").href; // http://example.com/sec/IF00.html 

and one below gets the value of the href attribute:

 document.getElementById("aaa").getAttribute("href"); // sec/IF00.html 
+106
Mar 15 '13 at 18:44
source share

document.getElementById("link").getAttribute("href"); If you have more than one <a> tag, for example:

 <ul> <li> <a href="1"></a> </li> <li> <a href="2"></a> </li> <li> <a href="3"></a> </li> </ul> 

You can do this as follows: document.getElementById("link")[0].getAttribute("href"); to access the first array of <a> tags or depends on the condition you are fulfilling.

+3
Jun 23 '16 at 12:46 on
source share

The href property sets or returns the value of the href attribute for the link.

  var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href'); var url="https://www.google.com/"; console.log( url+hello); 
0
Apr 17 '16 at 7:15
source share
 document.getElementById("aaa").href; //for example: http://example.com/sec/IF00.html 
-one
Apr 23 '15 at 5:15
source share

It is sad to see how many people gave such uncomfortable and uncomfortable answers. Here is the easiest way to get href:

 $("a").click(function(e){ var hash = this.hash; alert(hash); }); 

Everything is done in only one line of code. This is a flexible approach and does not rely on getting an element like previous answers.

-four
Jul 28 '17 at 15:45
source share



All Articles