I have an anchor tag that has a local href value, and a JavaScript function that uses the href value but directs it to a slightly different place than it would normally go. The 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 am requesting this, and it is because it will just make the page a lot cleaner. If it is not possible to get just the short href (as put in the anchor <a>
tag), then I could probably just insert an extra field into the tag, like link="sec/IF00.html"
, but again, that would be a little messier.
Use the querySelector() method to get an element by an href attribute, e.g. document. querySelector('a[href="https://example.com"]') . The method returns the first element that matches the selector or null if no element with the provided selector exists in the DOM.
The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!
The above anchor tag is a valid HTML tag, but it doesn't do much other than act as a placeholder. Let's use this anchor tag to link to a web page. You need to use the href attribute to link to another page. The value of the href attribute is usually a URL pointing to a web page (like the one above).
The below code gets the full path, where the anchor points:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
while the one below gets the value of the href
attribute:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
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 it like this: document.getElementById("link")[0].getAttribute("href");
to access the first array of <a>
tags, or depends on the condition you make.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With