I am a newbie..My question differs from other similar questions becuase I speak about the use of childNode to append or not. 1) Use jquery or DOM method?. 2)As it may be better to append a div etc as childNode so it does not interfer with the hieratical structure when removed from the parent." 3) I also ask if it is okay to use clone and childNode in the same process..
The reason I ask the question is beacuse I continually read that it is better to append a div etc as childNode so it does not interfer with the hieratical structure when removed from the parent. Make Sense! But then I go and see two tutorials from a respectable source and in Example 2 below they just append to the body without making it a childNode. Below are both examples I have seen. Thanks for your help.
Example 1
<!DOCTYPE html>
<html>
<body>
<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>
<p>Click the button to copy an item from one list to another.</p>
<button onclick="myFunction()">Try it</button>
<p>Try changing the <em>deep</em> parameter to false, and only an empty LI element will be cloned.</p>
<script>
function myFunction() {
var itm = document.getElementById("myList2").lastChild;
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
</script>
</body>
</html>
Example 2
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").clone().appendTo("body");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Clone all p elements, and append them to the body element</button>
</body>
</html>
My point is I am currently cloning using method 1 below without making it in to childNode. But I am willing to use method 2 if using childnode is the correct way? Also if the way I have adapted the code in method 2 is it correct? as it does work, or am I duplicating a duplicate?
Method 1: *what i use at the moment*
var cloned = $('.mydiv').first().clone();
$('.start-div').append(cloned);
Method 2: *I adapted it to use cloneNode*
var cloned = $('.mydiv').first().clone();
var myclone = cloned.cloneNode(true);
$('.start-div').appendChild(myclone);