简体   繁体   中英

clone element using next in js

I have a section in which contains two div, one div is created dynamically, now I would like to copy the other div which is not created dynamically into the div which is created dynamically

 let adContainer = $('#adContainer').html(); adContainer.next().html(adContainer);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="adContainer"> </div> <div style="width:100%; height:100%"> <video></video> </div>

This is not working, what is wrong here?

You should use the clone() and appendTo() methods of jQuery:

$('#adContainer').clone().appendTo($('#adContainer').next());

read more here: https://api.jquery.com/clone/

Also next() should be called directly on the element, not the html() of the element.

Your code don't work because you try to use next() with html and not with div . so you must select div and html in two variable like:

 let div =$('#adContainer'); let adContainer = div.html(); div.next().html(adContainer);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="adContainer"> <p>hello</p> </div> <div style="width:100%; height:100%"> <video></video> </div>

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