Can I pass a string variable to the <a href> tag to link to the website?

I'm a little new to web development, so I try to learn along the way. I have a 500 x 500 div. Inside this div, I have two divs, each 250x500. So my outer div is filled with two inner divs.

I have a setup so that when I click on the first div (left) the java script is called and the tooltip popup asks for the website url, which is then stored inside a string variable.

How can I make it so that the second div (right) will take the string variable from the alert box from the left div and put it in the href tag so that I can link to the website from the right div

Can the href tag take a value from a variable for its link? Maybe I'll get it all wrong, is there a better way I should be approaching this? Any help is appreciated!

+2


a source to share


2 answers


There's a method for creating the DOM:

// Create an element
var aEl = document.createElement("a");

// Ask the user for the URL
aEl.href = prompt("Please enter the website URL");

// Determine whether to use innerText or textContent
if ("innerText" in aEl)
    aEl.innerText = aEl.href;
else
    aEl.textContent = aEl.href;

// Add the link to the right div
document.getElementById("rightDiv").appendChild(a);

      



Or a straight forward innerHTML method:

var url = prompt("Please enter the website URL");
document.getElementById('rightDiv').innerHTML = '<a href="'+url+'">'+url+'</a>';

      

+2


a source


You can use:

document.getElementById('yourlink').href = 'entered link';



I haven't tested, but believe it should work.

0


a source







All Articles