添加链接元素<a> to paragraph <p> Javascript

时间:2015-12-08 02:18:10

标签: javascript jquery html css

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

如何添加<a>链接?

3 个答案:

答案 0 :(得分:4)

您不能混合innerHTML和createElement。您需要将元素附加到段落。

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>

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>

答案 1 :(得分:1)

使用innerHTML作为链接名称 和outerhtml获取elelmt的完整html

var temp_link = document.createElement("A");    
temp_link.href = "http://test.com";
temp_link.target = '_blank';
temp_link.innerHTML ='click here';

var par = document.createElement("P");
par.innerHTML = "some text: " + temp_link.outerHTML;     

document.getElementById("main_div").appendChild(par);

答案 2 :(得分:1)

这样的事情应该让你开始:

var $p = $("<p>").text("some text:");
$p.append( 
    $("<a>").attr("href", "http://test.com")
    .attr("target", "_blank")
    .text("click me") 
);
          
$("#main_div").append( $p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="main_div"></div>