Dynamically create HTML anchor tags using JavaScript

I have a question about anchor tags and javascript. Convert url to anchor tag

The text box accepts a URL (for example, "www.youtube.com")

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

How to do this so that the conversion button adds a link to a web page that will lead 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; } 
+5
source share
4 answers

You can generate elements and apply neede attributes to them. Then add a 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> 
+2
source

You can simply do this by adding a dynamic tag dynamically

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

Please see here for additional links.

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

0
source

 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> 
0
source

I assume that you know how to write JavaScript, so I won’t go there. The problem is understanding the target attribute of the <a> tag.

W3Schools: Goal Attribute

0
source

Source: https://habr.com/ru/post/1264397/


All Articles