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;
}
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? 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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With