Creating anchor tags dynamically in HTML using JavaScript
Asked Answered
C

4

11

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;  
}
Cottle answered 18/2, 2017 at 19:58 Comment(0)
T
8

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>
Tranship answered 18/2, 2017 at 20:13 Comment(1)
So far this is the only answer to include the target attribute which addresses the OP's question about opening in another tab, nice!Footprint
U
0

You can just do this by adding an anchor tag dynamically

var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',webpage);
aTag.innerHTML = "link text";
mydiv.appendChild(aTag);

Please have a look here for more references

How to add anchor tags dynamically to a div in Javascript?

Understanding answered 18/2, 2017 at 20:7 Comment(0)
P
0

function addLink()
{       
    var url = document.getElementById("link").value;
    var webpage = "http://" + url;
    
    var a = document.createElement("a");                 // create an anchor element
    a.href = webpage;                                    // set its href
    a.textContent = url;                                 // set its text
    
    document.getElementById("container").appendChild(a); // append it to where you want
}
a {
  display: block;
}
<div id="container"></div>
<br><br>
<input id="link"/><button onclick='addLink()'>ADD</button>
Peeler answered 18/2, 2017 at 20:8 Comment(0)
H
0

I assume you know how to write JavaScript, so I will not go there. The issue is understanding the target attribute of an <a> tag.

W3Schools: Target Attribute

Hurst answered 19/2, 2017 at 0:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.