How do I create a link using JavaScript? - javascript

I have a string for a title and a string for a link. I'm not sure how to put the two together to create a link on a page using JavaScript. Any help is appreciated.
The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs. I would like to link the titles to the URL to make the page useful.
I am using jQuery but am completely new to it and wasn't aware it could help in this situation.

<html>
<head></head>
<body>
<script>
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
</script>
</body>
</html>

With JavaScript
var a = document.createElement('a');
a.setAttribute('href',desiredLink);
a.innerHTML = desiredText;
// apend the anchor to the body
// of course you can append it almost to any other dom element
document.getElementsByTagName('body')[0].appendChild(a);
document.getElementsByTagName('body')[0].innerHTML += ''+desiredText+'';
or, as suggested by #travis :
document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
<script type="text/javascript">
//note that this case can be used only inside the "body" element
document.write(''+desiredText+'');
</script>
With JQuery
$(''+desiredText+'').appendTo($('body'));
$('body').append($(''+desiredText+''));
var a = $('<a />');
a.attr('href',desiredLink);
a.text(desiredText);
$('body').append(a);
In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.

Create links using JavaScript:
<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>
OR
<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>
OR
<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>

There are a couple of ways:
If you want to use raw Javascript (without a helper like JQuery), then you could do something like:
var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";
// and append it to where you'd like it to go:
document.body.appendChild(element);
The other method is to write the link directly into the document:
document.write("<a href='" + link + "'>" + text + "</a>");

<script>
_$ = document.querySelector .bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement( 'a' )
a.text = "Download example"
a.href = "//bit\.do/DeezerDL"
AppendLinkHere.appendChild( a )
// a.title = 'Well well ...
a.setAttribute( 'title',
'Well well that\'s a link'
);
</script>
The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear!
Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")
Leave the protocol open.
Instead of http://example.com/path consider to just use //example.com/path.
Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.
OffTopic: That's not really relevant about creating links in JS
but maybe good to know:
Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.

Dynamically create a hyperlink with raw JavaScript:
var anchorElem = document.createElement('a');
anchorElem.setAttribute("href", yourLink);
anchorElem.innerHTML = yourLinkText;
document.body.appendChild(anchorElem); // append your new link to the body

A dirty but quick way to create elements:
const linkHTML = `<a
class="my-link"
style="position: absolute; right: 0"
href="https://old.reddit.com"
title="Go to old reddit"
>
Old Reddit
</a>`;
// create element
const linkEl = strToElement(linkHTML);
// add element to document.body
document.body.appendChild(linkEl);
// utility function that converts a string to HTML element
function strToElement(s) {
let e = document.createElement('div');
const r = document.createRange();
r.selectNodeContents(e);
const f = r.createContextualFragment(s);
e.appendChild(f);
e = e.firstElementChild;
return e;
}

You paste this inside :
Click here

Related

Wrapping created elements in a span

Basically, I am trying to style our cookie policy banner but there is no HTML but only JS which generates the HTML.
I need to wrap both of the 'a' tags within a span but they are being created within a JS file.
Below is the JS snippet which is generating the 'a' tag.
function _createDismissLink(dismissText) {
var dismissLink = document.createElement('a');
_setElementText(dismissLink, dismissText);
dismissLink.id = dismissLinkId;
dismissLink.href = '#';
dismissLink.style.marginLeft = '24px';
return dismissLink;
}
I have tried to include a dismissLink.wrap( "<span class='test'></span>" );
But I've had no luck.
Any help would be much appreciated.
FOLLOWING ON FROM THIS
How would I go about wrapping this function and another function similar to it within a div?
Thank you
Try this:
var dismissLink = document.createElement('a');
_setElementText(dismissLink, dismissText);
dismissLink.id = dismissLinkId;
dismissLink.href = '#';
dismissLink.style.marginLeft = '24px';
var span = document.createElement('span');
span.appendChild(dismissLink);
return span;

Append data from div to link url

I am trying to have a div element on every page of my site that will contain the product number and then have a link that will put that number at the end.
For example,
<div id="productnumber">01101</div>
https://example.com/#
Then put the contents of the element with id "productnumber" after the # of the link.
Any idea if this is possible? Since this would make life easier than editing all existing pages and their respective php files.
Check for Element.innerHTML. You could use some inline JS and append it to the href-Attribute (which should be were id="purchaseurl" is now)
You can add a simple script to all your pages.
document.addEventListener("DOMContentLoaded", function() {
var productNumber = document.getElementById('productnumber').textContent;
Array.prototype.forEach.call(document.querySelectorAll('a[href~="purchaseurl"]'), function(link) {
// if you want to change the link
var currentHref = link.getAttribute('href');
link.setAttribute('href', currentHref + '#' + productNumber);
// if you want to change anchor text
var currentText = link.innerHTML;
link.innerHTML = currentText + productNumber;
});
});
<div id="productnumber">01101</div>
https://example.com/#
See getElementById, getElementsByTagName, and nextSibling.
var data = document.getElementById('productnumber'),
url = data.nextSibling.nextSibling;
url.innerText += data.innerText;
<div id="productnumber">01101</div>
https://example.com/#

Javascript link making target blank?

I have made a Javascript link maker...
document.write('http://imgur.com'.link('http://www.imgur.com'));
How I can make this open the link target in a new window, like target="blank"?
Here's a new "link builder" to override the built in link function, and its usage:
function mylink(url) {
return "" + this + ""
}
String.prototype.link = mylink
document.write('http://imgur.com'.link('http://www.imgur.com'));
You can use a function to add a link to a container. E.g.:
<div id="container"></div>
And the Javascript is:
addLink('value', 'http://jsfiddle.net');
function addLink(text, url){
var mydiv = document.getElementById("container");
var a = document.createElement('a');
a.setAttribute('href',url);
a.setAttribute('target','_blank');
a.innerHTML = text;
mydiv.appendChild(a);
}
This is a working JSFiddle JSFiddle

How to pass objects to a javascript function from HTML href link?

function createListItem(text1) {
var link = document.createElement("a");
var text = text1;
link.setAttribute("name", text);
link.setAttribute("href", "javascript:updateLevel1(text)");
//link.setAttribute("onclick", "updateLevel1()");
var list_item = document.createElement("li");
var list_text = document.createTextNode(text);
list_item.appendChild(list_text);
link.appendChild(list_item);
return link;
}
function updateLevel1(text) {
clearNavFrame2();
var link = document.createElement("a");
link.setAttribute("name", text);
link.setAttribute("href", "javascript:updateLevel1(text)");
link.appendChild(document.createTextNode(text));
document.getElementById("navigation_frame1").appendChild(link);
}
Here i want to pass the object text to the function updateLevel1 when i dynamically created an HTML link but unfortunately above code is not working. The function updateLevel1 is not able to figure out the object text. Am i doing something wrong?
Yes, you're doing something incorrectly. First, instead of setting the "href" attribute, you can add a "click" handler to the element:
var link = document.createElement('a');
link.onclick = function() { updateLevel1(text); };
There's really no reason to use "javascript:" URLs in a case like this.
Now, another problem you've got is that you create that <a> element but you don't append it to the document (in the code you posted). I suppose that somewhere, you use the return value from the "createListItem()" function and append it then. If not, well, nothing will really happen.
The reason that your "javascript:" value for "href" doesn't work is that you're setting up a situation wherein the browser will create a function from that string when the <a> is clicked. At that point, the local variable "text" from that function is long gone. When you use an actual function reference bound to the "onclick" property of the <a>, however, your function will retain access to that variable in its closure.
Just use an event handler:
function createListItem(text1) {
var link = document.createElement("a");
var text = text1;
link.setAttribute("name", text);
link.setAttribute("href", "#");
link.onclick = function(){
updateLevel1( text );
return false;
};
var list_item = document.createElement("li");
var list_text = document.createTextNode(text);
list_item.appendChild(list_text);
link.appendChild(list_item);
return link;
}
function updateLevel1(text) {
clearNavFrame2();
var link = document.createElement("a");
link.setAttribute("name", text);
link.onclick = function(){
updateLevel1( text );
return false;
};
link.setAttribute("href", "#" );
link.appendChild(document.createTextNode(text));
document.getElementById("navigation_frame1").appendChild(link);
}
You'll need to break your string and insert the value text has literally.
link.setAttribute("href", "javascript:updateLevel1('" + text + "')");
Just be careful - you may need to clean text if it contains any single quotes.
If this is a possibility you'll want to run something like text = text.replace("'", "\\'");
Try link.setAttribute("href", "javascript:updateLevel1(this);
Then you read it inside your function by its reference. eg:
function updateLevel1(elm) {
clearNavFrame2();
var link = document.createElement("a");
link.setAttribute("name", elm.name);
...
}

Replace Text with Image - JavaScript (getElementsByClass)

I have a span:
<span class="attr attr-value">Brand Name</span>
And I want to replace that text with an image, based on the text
Here is what I have:
<script type="text/javascript">
var oldHTML = document.getElementsByClass('attr-value').innerHTML;
var filename = oldHTML.toLowerCase().replace(/ /g, '-').replace(/([^0-9a-z-])/g,'');
var newHTML = "<img src='http://www.example.com/" + filename + ".jpg'>";
document.getElementsByClass('attr-value').innerHTML = newHTML;
</script>
What am I doing wrong here?
This line is an issue:
var oldHTML = document.getElementsByClass('attr-value').innerHTML;
document.getElementsByClass should be document.getElementsByClassName, and it returns a NodeList, which doesn't have an innerHTML property. You'd want to loop through the NodeList to look at the innerHTML of each element.
Something like this (live example):
<script type="text/javascript">
(function() {
var list, index, element, filename;
list = document.getElementsByClassName('attr-value');
for (index = 0; index < list.length; ++index) {
element = list[index];
filename = element.innerHTML.toLowerCase().replace(/ /g, '-').replace(/([^0-9a-z-])/g,'');
element.innerHTML = "<img src='http://www.example.com/" + filename + ".jpg'>";
}
})();
</script>
Changes:
Put the whole thing in an anonymous function and immediately execute that function, to avoid creating global symbols.
Use the correct getElementsByClassName
Loop through them
Operate on the innerHTML of each element.
Notes:
IE doesn't have getElementsByClassName, so you'll want to be sure you're loading a script that provides it on IE. That's not provided in the live example above, use Firefox, Chrome, or Opera. (Just search for "getElementsByClassName for IE" and you'll find several implementations to choose from.)
The above script tag will need to be placed after all of the elements you want to process in the HTML file.
class="attr attr-value" and you're calling
document.getElementsByClass('attr-value').innerHTML
document.getElementsByClassName();
It should be, (e.g)
document.getElementsByClassName('attr-value')[0];

Categories