Insert current URL into a link using JS and HTML - javascript

So, Ive read through similar things but I still can't find an answer that applies more closely to what I'm doing. I am attempting to use JS to get the current page URL and append it to a social media sharing link like this:
<a href="http://reddit.com/submit?url=CURRENTPAGE.html; title="This is a post!" target="_blank">
Using Javascript, I've managed to assign the current URL to a variable:
<script>
var x = window.location.href;
document.getElementById("smsharing").innerHTML = x;
</script></p>
And I made sure it worked by doing a test display of it. So what exactly is the proper method/syntax for actually putting 'x' in place of CURRENTPAGE.html???
I know this is a STUPID question, but I'm really stumped. Specifics help, because part of the problem is that I have precious little knowledge of JS. Thoughts?

This should do it:
<script>
baseurl="http://www.facebook.com?"
function buildURL(item)
{
item.href=baseurl+window.location.href;
return true;
}
</script>
</head>
<body>
<a onclick="return buildURL(this)" href="">Google</a>
</body>

Get the elements current href which doesn't have the url value and append the current url.
Modified HTML
<a id='smsharing'
href="http://reddit.com/submit?url="
title="This is a post!"
target="_blank">link</a>
Script
<script>
var x = window.location.href;
var link = document.getElementById("smsharing"); // store the element
var curHref = link.getAttribute('href'); // get its current href value
link.setAttribute('href', curHref + x);
</script>

Using just pure JavaScript you can set the href of the link by just having the base href as a string and then add the variable where ever it is needed.
var x = window.location.href;
document.getElementById("linkid").href = "http://reddit.com/submit?url="+encodeURIComponent(x);

Using jQuery it is as simple as:
$('a').attr("href",x);

You should simply replace innerHTML by href :
document.getElementById("smsharing").href = x;
Hope this helps.

Once you have access to the current URL, you then want to find the element and replace CURRENTPAGE.html. To do so, you'll need some way to select the element. Let's give it an ID:
<a id="myLink" href="http://reddit.com/submit?url=CURRENTPAGE.html"></a>
Now we can grab the link like so:
var link = document.getElement('myLink');
Let's get the URL again, and give it a better variable name:
var url = window.location.href;
Now let's update the HREF attribute of link:
link.href = link.href.replace('CURRENTPAGE.html', url);
And that's it!

Create another variable for the complete href attribute of your link:
var myURL = "http://reddit.com/submit?url=" + x;
Then replace the current href attribute with that variable:
docment.getElementById("YourLinkTagID").href = myURL

Related

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

Javascript that changes specific href link to new one? (no jquery)

Friends, can you give me simple javascript that will change href link with new one on all posts in my blogger blog.
<a href="http://domainone.com/brb.php">
to become
<a href="http://domaintwo.com/brb.php">
the problem is that domainone is no longer available and I need a mass change when user asks for this domain to be directed to the new one.
please no jquery only oldschool javascript.
Regards!
you can use .setAttribute(), something like this:
var links = document.getElementsByTagName('a')
for(var i=0;i<links.length;i++){
if(links[i].getAttribute('href') && links[i].getAttribute('href').indexOf('domainone') >=0 )
links[i].setAttribute('href', 'http://domaintwo.com/brb.php');
}
link
//If you want to change All a tags href, Use it
var aTags = document.querySelectorAll('a');
for (var tag of aTags) {
tag.setAttribute('href','http://domaintwo.com/brb.php');
}
//If you want to change specific one, Use it.
var aTag = document.querySelector('#first');
aTag.setAttribute('href','https://stackoverflow.com//posts/45746835');
a
b
c
Try This.
The important thing is using setAttribute

Replace a href with a js function call

I want to replace an url in a href with a call of a function that needs to include the url.
example:
I have the following string:
Google
some other text
Wikipedia
I want to get back a string like this:
Google
some other text
Wikipedia
I have tested some ways with RegEx, but I'm not good with RegEx. Does anyone have a solution for my problem?
EDIT:
Sorry, I forgot to write. I'm building an appcelator application. I can't use jQuery or "document". I think the only way is a RegEx.
Give this regex a try:
/href="([^"]+)/g
Here is a sample of its usage (JsFiddle Demo)
var subject = 'Googlesome other textWikipedia';
var result = subject.replace(/href="([^"]+)/g, 'href="javascript:anyFunction(\'$1\')');
If you give your hrefs unique IDs you can do this:
var val = $("#myHref").attr("href");
$("#myHref").attr("href", "javascript:anyFunction('"+val+"');");
If you want to avoid unique IDs then you can do this (applied to all a's):
​$("a").each(function() {
var val = $(this).attr("href");
$(this).attr("href", "javascript:anyFunction('"+val+"');");
});​​​
If you want to avoid applying this to all hrefs you can give all the hrefs you want changed a class then use a selector like this: $(".hrefToModify")...
NEW:
If you can use javascript, then can you get access to the anchor tag itself? if so:
anchor_element.href = "javascript:anyFunction('" + anchor_element.href + "')";
OLD:
<a id="link1" href="www.google.com">Google</a>
some other text
<a id="link2" href="www.wikipedia.org">Wikipedia</a>
<script>
document.getElementById('link1').addEventListener('click', function(e) {
alert('hello');
e.preventDefault();
return false;
});
</script>

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");

How to get "raw" href contents in 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.

Categories