Solution 1 :

use Element.getAttribute() function to get the value of href attribute. This function returns the value of the specified attribute.

getElementsByTagName("a")[0].getAttribute('href')
console.log(document.getElementsByTagName("a")[0].href)
console.log(document.getElementsByTagName("a")[0].getAttribute('href'))
<a href="corners/xyz.csv">Data</a>

Solution 2 :

Read the attribute, not the property

var anchor = document.querySelector("a")
console.log(anchor.getAttribute('href'))
<a href="foo/bar.baz"></a>

Solution 3 :

document.getElementsByTagName("a")[0].getAttribute("href");

Solution 4 :

document.getElementsByTagName("a")[0].getAtrribute("href") should do the trick.

Solution 5 :

pathname is the property you are looking for,

console.log(document.querySelector('a').pathname);
<a href="corners/xyz.csv">Data</a>

Solution 6 :

Per this answer I discovered that the property resolves to an absolute URL while the attribute remains the string value you want. In your case (since you are grabbing all the a tags) you would want to map them.

let rawHrefs = [...document.getElementsByTag('a')]
  .map(el => el.getAttribute('href'));

Problem :

I have a static HTML that I generate using a script.

My hyperlinks in the HTML look like this:

<a href="corners/xyz.csv">Data</a>

They corners directory is present in the same directory where the HTML resides. When I open this using my browser, the browser resolves the URL which becomes something like:

/home/user/blah/blah1/corners/xyz.csv

I want to use the href value in some part of my javascript function. When I do getElementsByTagName("a")[0] i get the entire resolved URL.

But, all I want is corners/xyz.csv

Is there a way to get the text that is present in the href tag without resolving it ?

By

Leave a Reply

Your email address will not be published. Required fields are marked *