How to get "raw" href contents in JavaScript - javascript

I am trying to write a GreaseMonkey script in which I want to find all of the links that are relative links. It seemed to me that the way to do that would be to match the contents of href against /^https?:///.
But I find that when I access the anchor's href attribute, it's always normalized or cooked into a form that contains "http". That is, if the HTML contains:
<a id="rel" href="/relative/link">inner</a>
accessing
document.getElementById("rel").href
returns
http://example.com/relative/link
How can I access the raw data in the href attribute?
Alternately, is there a better way to find relative links?

Try the getAttribute method instead.

Typical. I figured it out myself almost immediately after posting the question.
instead of:
anchor.href
use:
anchor.getAttribute("href")
Of course, it took me longer to type in this answer than it took everyone else to answer it. (Damn, you people are fast.)

Here's a code snippet you could run to test.
const anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
let hrefFullPath = anchor.href;
let hrefRelativePath = anchor.attributes.href.value;
console.log('hrefFullPath', hrefFullPath);
console.log('hrefRelativePath', hrefRelativePath);
}
Let's say, you are at http://localhost:4200, and this is your document as you have shown in the question.
<a id="rel" href="/relative/link">inner</a>
This anchor's attribute value of href is:
document.getElementById('rel').attributes.href.value => /relative/link
And anchor's href value is:
document.getElementById('rel').href => http://localhost:4200/relative/link
I hope it helps.

Get the link dom and add attributes for same and append the actual link to same.
var hrefUrl = 'https://www.google.com/';
const link: HTMLLinkElement = dom?.createElement('link');
link.setAttribute('rel', 'canonical');
link.setAttribute('id', 'seo');
dom?.head?.appendChild(link);
dom?.getElementById('seo')?.setAttribute('href', hrefUrl);
// working
Hope this will work for dynamic links that to append for each dynamic pages under js / ts.

Related

Why will the colour of the active link not highlight blue? [duplicate]

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.
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>
</li>
<li>
</li>
<li>
</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.
This code works for me to get all links of the document
var links=document.getElementsByTagName('a'), hrefs = [];
for (var i = 0; i<links.length; i++)
{
hrefs.push(links[i].href);
}
In my case I had a href with a # and target.href was returning me the complete url. Target.hash did the work for me.
$(".test a").on('click', function(e) {
console.log(e.target.href); // logs https://www.test.com/#test
console.log(e.target.hash); // logs #test
});
The href property sets or returns the value of the href attribute of a link.
var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
var url="https://www.google.com/";
console.log( url+hello);
document.getElementById("aaa").href; //for example: http://example.com/sec/IF00.html

Trying to learn JavaScript and use it to return only the address not the whole <a> tag

Hello and thank you in advance for any and all assistance.
I'm trying to teach myself the basics of JavaScript before I start a bootcamp. In the Prep course we are asked to return the header, first link text and first link href using document.querySelector(). The course showed us how to do the header and I was able to get the first link text. What I cannot seem to figure out is how to return JUST the address and NOT the whole tag.
Some of the things I've tried:
document.querySelector('a href')
document.querySelector('a href=')
document.querySelector('a href=""')
document.querySelector('a').innerHTML
document.querySelector('a').innerText
document.querySelector('a href').innerHTML
document.querySelector('a href').innerText
Thanks again.
John
First Understand that href is an attribute, not an element, anchor is an element that accepts href as the attribute to get this attribute value you need to first get that anchor element then get its attribute value. For example:
let anchor = document.querySelector("a");
let url = anchor.getAttribute("href");
console.log(url)
`
let anchor = document.querySelector("a");
let url = anchor.getAttribute("href");
console.log(url)
<a href='https://stackoverflow.com/' tittle='stackOverflow'Stack Overflow></a>
`
document.querySelector("a").getAttribute("href")
You can try something like this, to bring any attribute of the anchor tag
document.querySelector('a').attributes.href.value

How to check if link is present on a page with Jquery?

I have this link on my web page:
Terms and conditions
I want to use Jquery to check whether this specific link is present or not on the web page. I know how to check if text is present on a page, but am struggling a little with links. If it helps, it is only the terms-conditions-mywebsite bit that I need to use (as mywebsite changes depending on who is using the site).
The class is footer so I have tried $('.footer:contains("terms-conditions") but this doesn't seem to work. Any pointers would be appreciated, thanks so much :)
Edit: I need to check that the actual specific contents of this links is present, rather than the text 'Terms and conditions'
You should check the value of href attribute. You can use Attribute Contains Selector [name*=”value”] which select elements that have the specified attribute with a value containing a given substring:
The following should work:
if($('a[href*=terms-conditions]').length){
//exist
}
OR: Check the link string directly
if($('a:contains("Terms and conditions")').length){
//exist
}
I would look at doing this with Javascript, as it's very straightforward and means you are not reliant on JQuery should you wish to remove JQuery from the site at a later date.
// get <a> elements
var links = document.getElementsByTagName('a');
// loop through each <a>
for (var i = 0; i < links.length; i++) {
// get each href
var hrefs = links[i].getAttribute("href");
// check href against the one you want
if (hrefs == "https://www.google.com") {
// check content of link
console.log('link content:', links[i].innerHTML)
}
}

How can i edit the href of this specific class via Javascript?

I can figure out how i can change this href link via Javascript, can you guys help me?
The link i want to change is the above:
Html Screenshot of the Link here
<div class="view-project vp-global font_rs0r6bbli">SABER MAIS</div></div><div class="section">
You can use document.querySelector('.view-project.vp-global.font_rs0r6bbli a').href to set the href value of the a tag in that class. Use browser's inspect element on that link to check the href value being changed.
var newHref = 'www.google.com';
document.querySelector('.view-project.vp-global.font_rs0r6bbli a').href = newHref;
<div class="view-project vp-global font_rs0r6bbli">SABER MAIS
You can fetch elements using the query selector..
let element = document.querySelector('.fp-tableCell .view-project.font_re0r6bbli a');
element.href="example.php";
but rather than fetching an element by its class I would recommend to use an specific id.

make hyperlink from javascript

I want to use a hyperlink string in HTML page which I want to declare source link (URL) in my js file. Please tell me how can I call that URL from my js into html.
Thanks
There are a number of different ways to do this. You could use document.createElement() to create a link element, and then inject the element into the DOM. Or you could use the .innerHTML property of an element that you already have on the page to insert the link using text. Or you could modify the "href" attribute of an existing link on the page. All of these are possibilities. Here is one example:
Creating/Inserting DOM Nodes with DOM Methods
var link = document.createElement('a');
link.textContent = 'Link Title';
link.href = 'http://your.domain.tld/some/path';
document.getElementById('where_to_insert').appendChild(link);
Assuming you have something like this in your HTML:
<span id="where_to_insert"></span>
Creating/Inserting DOM Content with innerHTML
And another example using innerHTML (which you should generally avoid using for security reasons, but which is valid to use in cases where you completely control the HTML being injected):
var where = document.getElementById('where_to_insert');
where.innerHTML = 'Link Title';
Updating the Attributes of a Named DOM Node
Lastly, there is the method that merely updates the href attribute of an existing link:
document.getElementById('link_to_update').href = 'http://your.domain.tld/path';
... this assumes you have something like the following in your HTML:
<a id="link_to_update" href="javascript:void(0)">Link Title</a>
Try this:
var alink = document.createElement("a");
alink.href = "http://www.google.com";
alink.text = "Test Link";
document.getElementsByTagName("body")[0].appendChild(alink)
From whatever I understand, You want to update href with JS variable.
You can use Jquery to achieve it.
try $("a").attr("href", js_variable)
Refer this for more details
How to change the href for a hyperlink using jQuery
It seems like you would be able to do something like this:
Using Javascript.
var col2= document.getElementById('id_Of_Control');
col2.innerHTML="<a href='page2.html?" + params + "'>Page 2</a>";
where col2 is another container control something like div,span, or any.
Using jQuery.
Here I will recommend you to Use jQuery. So you can be more dynamic.
$("#col2").append("Page 2");
OR
$("#col2").after("Page 2");
OR
$("#col2").before("Page 2");

Categories