3

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 ?

lonely
  • 681
  • 1
  • 7
  • 10

6 Answers6

3

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>
Yousaf
  • 27,861
  • 6
  • 44
  • 69
1

Read the attribute, not the property

var anchor = document.querySelector("a")
console.log(anchor.getAttribute('href'))
<a href="foo/bar.baz"></a>
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

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

Murat
  • 34
  • 5
1

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

1

pathname is the property you are looking for,

console.log(document.querySelector('a').pathname);
<a href="corners/xyz.csv">Data</a>
JavaScript
  • 539
  • 2
  • 10
1

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'));
Sukima
  • 9,965
  • 3
  • 46
  • 60