简体   繁体   English

如何克隆元素并将其他el追加到克隆?

[英]How can I clone element and append to the clone another el?

I have some id div with elements(classes and Ids), I need to clone it and append to my clone new class. 我有一些带有元素(类和ID)的id div,我需要对其进行克隆并将其追加到克隆的新类中。 How can I do it? 我该怎么做?

 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> 

use following code 使用以下代码

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

Using JQuery, 使用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.

You should reference JQuery to your page. 您应该将JQuery引用到您的页面。 Tell me if it works. 告诉我是否可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM