Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Link Element <a> to paragraph <p> Javascript

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?

like image 436
spen123 Avatar asked Feb 09 '23 08:02

spen123


1 Answers

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>
like image 200
epascarello Avatar answered Feb 10 '23 21:02

epascarello