I am trying to add a link into a paragraph that already has some text in it, but when I try this is just adds the text of the link element and not actual link. href or <a>
tag. Here is html
<div id="main_div"></div>
And here is Javascript
var temp_link = document.createElement("A");
temp_link.href = "http://test.com";
temp_link.target = '_blank';
var par = document.createElement("P");
par.innerHTML = "some text: " + temp_link;
<!--I have also tried this line below -->
<!-- par.insertAdjacentHTML('beforeend', '<div><a>' + url +'</a></div>' -->);
document.getElementById("main_div").appendChild(par);
I have tried two things what is in the above javascript both what it would currently run and the line that is commented out, neither attach the link, they just add the text I have included JSFiddle.
How can I add it so that <a>
links?
You can not mix innerHTML and createElement. You need to append the element to the paragraph.
var temp_link = document.createElement("a");
temp_link.href = "http://test.com";
temp_link.target = '_blank';
temp_link.innerHTML = "link";
var par = document.createElement("p");
par.innerHTML = "some text: ";
par.appendChild(temp_link);
document.getElementById("main_div").appendChild(par);
<div id="main_div"></div>
or
var temp_link = document.createElement("a");
temp_link.href = "http://test.com";
temp_link.target = '_blank';
temp_link.innerHTML = "link";
var text = document.createTextNode("some text: ");
var par = document.createElement("p");
par.appendChild(text);
par.appendChild(temp_link);
document.getElementById("main_div").appendChild(par);
<div id="main_div"></div>
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