简体   繁体   中英

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. 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,

 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. Tell me if it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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