Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating anchor tags dynamically in HTML using JavaScript

I have a question about anchor tags and javascript.Converting a URL to an anchor tag

The text box accepts a url (eg. "www.youtube.com")

I made a Javascript function that adds "http://" to the link.

How do I make it so the convert button adds a link on the webpage that takes you to the website in another tab.

My Javascript code is as follows:

var webpage="";
var url="";
var message="";
var x= 0;
var page="";

function convert()
{       
    url=document.getElementById("link").value;
    webpage = "http://" + url;  
}
like image 964
Kyle Goertzen Avatar asked Feb 18 '17 19:02

Kyle Goertzen


People also ask

How do you create an anchor in JavaScript?

Create an anchor <a> element. Create a text node with some text which will display as a link. Append the text node to the anchor <a> element. Set the title and href property of the <a> element.

Can we use anchor tag in JavaScript?

Can we use anchor tag in JavaScript? Using JavaScript In vanilla JavaScript, you can use the document. createElement() method, which programmatically creates the specified HTML element. The following example creates a new anchor tag with desired attributes and appends it to a div element using the Node.

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

Answer: Use the jQuery . attr() Method attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.


1 Answers

You could generate the elements and apply the needed attributes to it. Then append the new link to the output paragraph.

function generate() {
    var a = document.createElement('a');
    
    a.href = 'http://' + document.getElementById('href').value;    
    a.target = '_blank';
    a.appendChild(document.createTextNode(document.getElementById('href').value));
    document.getElementById('link').appendChild(a);
    document.getElementById('link').appendChild(document.createElement('br'));
}
Link: <input id="href"> <button onclick="generate()">Generate</button>
<p id="link"></p>
like image 63
Nina Scholz Avatar answered Sep 18 '22 15:09

Nina Scholz