Creating anchor tags dynamically in HTML using JavaScript

13,319

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>
Share:
13,319

Related videos on Youtube

Kyle Goertzen
Author by

Kyle Goertzen

Updated on August 22, 2022

Comments

  • Kyle Goertzen
    Kyle Goertzen over 1 year

    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;  
    }
    
  • j3py
    j3py about 7 years
    So far this is the only answer to include the target attribute which addresses the OP's question about opening in another tab, nice!