我怎样才能克隆元素并附加到克隆另一个el?

时间:2017-04-24 14:15:59

标签: javascript jquery html

我有一些带有元素(类和ID)的id div,我需要克隆它并附加到我的克隆新类。我该怎么办?



window.onload = Func ();

function Func () {

var temp = document.getElementById("start");
var cl = temp.cloneNode(true);
var div = document.createElement('div');
div.className = "class";
div.innerHTML = "MyText";
var result = cl.getElementById("second").append(div);
alert(result.innerHTML);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="start">
<div id="second">
<a href="#">Link</a>
</div></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:-1)

使用以下代码

$(function(){
  var $Div = $('.start').clone();
  $('.second').html($Div);
});

答案 1 :(得分:-1)

使用JQuery,

 var clone = $("#divName");
 or var clone = $(".className")

 var secondDiv = $("#secondDiv");
 or var secondDiv = $(".secondDivClassName");
 //Or you can get the html of your second div like this:
 var myHtml = secondDiv.html(); //if you don't give any parameter, it takes the inner html of the given element.

 //and finally insert your html into the clone like this :
 clone.html(myHtml);// in this case, the html() methode takes a parameter and inserts the given parameters into the given element.

您应该将JQuery引用到您的页面。 告诉我它是否有效。