How can I add "href" attribute to a link dynamically using JavaScript? - javascript

How can I add the href attribute to a link dynamically using JavaScript?
I basically want to add a href attribute to <a></a> dynamically (i.e. when the user clicks on specific image in the website).
So from:
<a>Link</a>
I need to go to:
Link

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

I assume you know how to get the DOM object for the <a> element (use document.getElementById or some other method).
To add any attribute, just use the setAttribute method on the DOM object:
a = document.getElementById(...);
a.setAttribute("href", "somelink url");

document.getElementById('link-id').href = "new-href";
I know this is an old post, but here's a one-liner that might be more suitable for some folks.

First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.
Then, add something like this in the javascript function that you're calling:
var abc = 'somelink';
document.getElementById('test').innerHTML = 'Link';
This way the link will look like this:
Link

More actual solution:
<a id="someId">Link</a>
const a = document.querySelector('#someId');
a.href = 'url';

I know there seems plenty good answers here, but none of them seemed simple enough for what I was "told" to do in the 2022 Udemy Web Development Bootcamp by Angela.
So I remembered how simple the use of scriplets was and figured to try it and it works just as well.
For those like me who are learning let me explain:
. - takes you to current URL
then static path
then dynamic variable generated for each post (its a blog website)
Read More
This is using JS inside an EJS page
same solution is also given in the solution lecture of the bootcamp here:
https://www.udemy.com/course/the-complete-web-development-bootcamp/learn/lecture/12385596#overview
Lecture 317

I came here because I wanted to dynamically set the link href after it's been clicked
<a id='dynamic'>link text</a>
document.getElementById("dynamic").addEventListener("click", onClick_dynamic)
function onClick_dynamic(e){
const nextPage = getNextPage()
document.getElementById("dynamic").href = _BASE_URL + "?nextPage=" + nextPage
// e.default processing sends user to href
}

Single line solution
<a id="yourId">Link</a>
document.querySelector("#yourId").href("URL")

enter code here javasicript added
var x = "www.google.com";
vay y = "550";
var z= x+y;
document.write('GONDER');

Related

How to dynamically add data from a span tag into a href tag

I think this may have a simple answer that I'm missing. The following tag inserts a TV show name into any page on my website:
<span class="show-title"></span>
what I'm trying to do is incorporate that data dynamically into a HREF URL link.
So, let's say on the page I'm on:
produced the result: GOTHAM.
I'd like to then use that data to create this url:
https://en.wikipedia.org/wiki/GOTHAM_(TV_series)
So I'm trying stuff like:
</span>_(TV_series)"> Link
or
Link
nothing working - any help would be awesome. Thanks!
You could do something like this:
In HTML
<a class="wikipedia-link">Link</a>
And your JavaScript function:
setLink(showTitle) {
var link = document.getElementsByClassName("wikipedia-link");
link.setAttribute("href", "https://en.wikipedia.org/wiki/" + showTitle + "_(TV_series)");
}
The html you use is wrong. span shouldn't be inside tag a. No tag inside another.
If your result is in javascript variable, you can set the url using jquery.
$('a').attr('href', "https://en.wikipedia.org/wiki/" + result + "_(TV_series)");
result variable is your desired result.
Although there's better ways of going about doing this, I'm going to answer the question in the context in which you presented it:
First, give the url link a class or ID so you can easily select it with JavaScript to change the href value later. Also, don't try to nest the span tag anywhere inside the a tag. Leave it outside.
<span class="show-title">GOTHAM</span>
Link
Next, in a JavaScript file or a <script> tag, define your variables:
var showTitle, showWikipediaLink, linkElement
Then, assign value to your newly defined variables
linkElement = document.querySelector('.show-wikipedia-link');
showTitle = document.querySelector('.show-title').innerText;
showWikipediaLink = 'https://en.wikipedia.org/wiki/' + showTitle + '_(TV_series)';
Finally, use JavaScript to update the href value of the link element to the show's Wikipedia link:
linkElement.href = showWikipediaLink;

Select all anchor tags based on href and Change it

i have a question regarding changing URL of anchor tags based on HREF.
What i do to select all anchor tags is like this:
var anchortags = document.querySelectorAll("a[href*='secureloan.asim.no']");
With this i select all anchor tags that refers to secureloan.asim.no
What i want also is to CHANGE the links when user click on it (i want to remove a parameter)
example of URL can be:
Example URL:www.secureloan.asim.no/oasis/index.html#/no/asim?lang=nb-no&product=lev&lanekilde=&campaigncode(etc....).
i want to remove "lanekilde=" from the parameter. im using this code:
String(document.location.href).replace("&lanekilde=", "");
This gives me right URL but how do i change it for all users on website when they click on it.
Code ive made til now:
var anchortags= document.querySelectorAll("a[href*='secureloan.remember.no']");
String(document.location.href).replace("&lanekilde=", "");
thank you :)
PS: NO Jquery please!
PS: im using tag manager if anyone has a idea of different way
You just need to iterate over the nodeset and change each one in turn:
var anchortags = document.querySelectorAll("a[href*='secureloan.asim.no']");
anchortags.forEach(function(tag) {
tag.href = tag.href.replace('&lanekilde=', '');
});

Show URL in browser when link added with javascript

I have added an onclick function to a div here:
<script type="text/javascript">
document.getElementById("fab").onclick = function() {
location.href = 'http://your.url.here';
}
</script>
When you hover over the div, it doesnt show the URL in the bottom left of the browser like an anchor tag does (see picture): http://i.stack.imgur.com/iGLHS.png
Is there any way to make the browser show the link, when it has been added with javascript?
Add the title attribute to your element:
<div id="fab" title="http://your.url.here'></div>
Actually this is different than the popup you're seeing, but it might be as close as you can get.
As #Benten points out, you'd have to set window.status, which isn't allowed by most modern browsers.
I don't think you can directly access the property that you are looking for any more. Usually it's ignored. See this: http://www.w3schools.com/jsref/prop_win_status.asp . I'd say the other answer is your best bet.
I think something different. I hope i didnt understand it wrong. If you add -a- element as parent to your -div- it acts like what you want.
var element = document.getElementById("fab");
var aa = document.createElement("a");
aa.setAttribute('href', 'http://www.google.com');
var parent = element.parentNode;
parent.insertBefore(aa, element);
aa.appendChild(element);
please let me know if i understand it wrong?

Using regexes to modify the text of html (with javascript)

I want to modify the text in a html file using javascript in an android webview.
Essentially, I want to do what android Linkify does to text, but I don't want to do it with java code, because I feel like that might delay the webview rendering the html (if I parse the text before sending it to the webview).
So, for example a piece of html like this:
<html>
<body>
google.com <!--these two shouldn't be linked-->
akhilcherian#gmail.com <!--these two shouldn't be linked-->
<p>www.google.com</p> <!--this should be linked-->
<p>102-232-2312 2032-122-332 </p><!-- should be linked as numbers-->
</body>
</html>
Should become this:
<html>
<body>
google.com
akhilcherian#gmail.com
<p>www.google.com</p>
<p>102-232-2312 <a href="tel:2032-122-332>2032-122-332</a> </p>
</body>
</html>
I already have the regexes to convert numbers and email ids to links, and they're working well enough. What I want to ensure is that I don't link anything that's already within tags. I've removed anchor tags, so they're not an issue, but I also need to avoid linking things like this:
<div width="1000"> <!-- Don't want this '1000' to be linked (but I do want other 4 digit numbers to be)-->
So for example if my regex for links is:
var replacePattern1 = /((https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim
How do I make sure that it's not within < and >? (Answers using javascript would be appreciated, but if you feel like this is a stupid way of doing it, please let me know about alternatives).
If you're answering with javascript, this question can essentially be shortened to:
How do I write a regex in javascript to search for patterns which are not surrounded by '<' '>' tags
So if you use JS than mean is client side, your DOM page have free access of all objects of your page coef events.
May be in this step you dont need to use a regex just using DOM.
jquery lib can easy update DOM object.
in your step you want only tag.
So i suggest :
//using jquery
$("p").each(function(){
console.log($(this))
});
//js
var paras = document.getElementsByTagName("p");
for(p in paras){
console.log(paras[p])
}
As i tell you the deal is manipulate the DOM so example with you step dunno if exactly what you try to get :
var paras = document.getElementsByTagName("p");
var hrefs = [];
//what you want to replace in the loop of p
var json_urls = {"links":["http://", "tel:"]};
for(p in paras){
//copy of text content of your p
var text_cp = paras[p].textContent;
//delete the p[i] content
paras[p].textContent = "";
//create element dom a
hrefs[p] = document.createElement("a");
//i add attribute id with some affectation unique
hrefs[p].id = "_" + p;
//add attribute href to a with some affectation replace + content
hrefs[p].href = json_urls.links[p] + text_cp;
hrefs[p].textContent = text_cp;
paras[p].appendChild(hrefs[p]);
}

Javascript: replace a string in element.src attribute

Hi I am currently trying to replace a query string value in a a link's src attribute.
it works fine in firefox but not in ie.
example:
<a id="link" href="#" src="http://somedomain.com?id=123&size=20">link</a>
then on my js it looks kinda like this:
var link = document.getElementById('link');
link.src.replace('size=20', 'size=45');
in ie, it returns something like src is not an object error;
anyone kind enough to lend a hand?
also, i need this to be on native javascript so please don't suggest a framework as a solution thanks.
To get it to work in IE you're going to need to use link.setAttribute('src', ...).
use:
var link = document.getElementById('link');
var src = link.getAttribute("src").replace('size=20', 'size=45');
link.setAttribute("src", src);
Well, links (anchor elements) don't have a src attribute, I think that you want to change the href attribute:
var link = document.getElementById('link');
link.href = link.href.replace('size=20', 'size=45');
In your case the "src" attribute in your link is an expando attribute, since an anchor tag does not have a src.
When working with expando attributes, it's safest to set and get the values using the setAttribute('attributeName',***value*)** and getAttribute('attributeName') accessors.
To find out more about getAttribute and setAttribute you can check here:
https://developer.mozilla.org/en/DOM/element.getAttribute
https://developer.mozilla.org/en/DOM/element.setAttribute
To find out more about DHTML properties you can check the MSDN Resource here:
http://msdn.microsoft.com/en-us/library/ms533055%28VS.85%29.aspx
Example Code using getAttribute and setAttribute:
var link = document.getElementById('link');
var src = link.getAttribute('src');
link.setAttribute('src',src.replace('size=20','size=40'));
I believe getAttribute is more cross-browser friendly.
var link = document.getElementById('link');
var result = link.getAttribute("src").replace('size=20', 'size=45');
Also, the replace function returns a string. It doesn't operate on the string it is called against. This means you have to assign the result.
link.setAttribute("src", result);

Categories

Resources