3

I have heard few approaches:

  1. I could simply iterate through 20k elements and do appendChild.
  2. I could insert All items into newly created div in js and then just put that div into parent dom.
  3. Is there any other approach? Copy html wholesale?

However, I am confused on how to do 2. What is the best way to move all child element from div A to div B without iterating over all of them.

7
  • Please show the exact structure of source and target elements. Commented Jan 9, 2016 at 22:18
  • @cFreed here ` arr = [ domElement , domElement , domElement , domElement .....] ` Commented Jan 9, 2016 at 22:20
  • 2
    DocumentFragment Commented Jan 9, 2016 at 22:22
  • 1
    Nothing wrong with that! I knew JavaScript for so many years before jQuery came along that I can't imagine what we did without it. Commented Jan 9, 2016 at 22:40
  • 1
    @DaveKaye i am opposite i started with jquery and bee learning js since then Commented Jan 9, 2016 at 23:25

3 Answers 3

4

You can also use document fragment which appends all at one moment

  var fragment = document.createDocumentFragment();
  fragment.appendChild(...)
  fragment.appendChild(...)
  ...
  element.appendChild(fragment)
Sign up to request clarification or add additional context in comments.

Comments

2

According to this source the fastest is to simply iterate through the elements and append them.

Far better than creating a random div is to create a document fragment and append to that fragment. Then, said fragment can be added to the dom

var fragment = document.createDocumentFragment()
arr.forEach(el => fragment.appendChild(el))
element.appendChild(fragment)

I made a jsPerf that contains an experiment about which of these two are faster. It appears that using document fragment is the same as raw append with my limited test (one browser, one OS)

Comments

1

Why not just using cloneNode() in deep mode:

// Copy the element and its child nodes
var cln = itm.cloneNode(true);

// Append the cloned element to the new div with id="new_div"
document.getElementById("new_div").innerHTML(cln);

Hope this helps.

2 Comments

wont this result in additional element in destination element
eleA -> '' empty " & eleB -> "children, children, children" ......after this...... eleA -> '' eleB -> "children, children, children" " & eleB -> "children, children, children"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.