Reputation: 681
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 ?
Upvotes: 3
Views: 5182
Reputation: 29314
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>
Upvotes: 4
Reputation: 10084
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'));
Upvotes: 1
Reputation: 539
pathname
is the property you are looking for,
console.log(document.querySelector('a').pathname);
<a href="corners/xyz.csv">Data</a>
Upvotes: 1
Reputation: 11
document.getElementsByTagName("a")[0].getAtrribute("href")
should do the trick.
Upvotes: 1
Reputation: 207527
Read the attribute, not the property
var anchor = document.querySelector("a")
console.log(anchor.getAttribute('href'))
<a href="foo/bar.baz"></a>
Upvotes: 1