0

I have a question regarding, creating elements in javascript

what is the best approach when it comes to for example adding properties to a newly created element and what is better performance wise?

So question being as follows:

  1. Create the element
  2. Set the id property of the element
  3. Append
  4. THEN use the created element by refrencing its ID and adding new properties

OR

  1. Create the element
  2. Set the all sorts of properties of the element in question
  3. Append

Thanks!

EDIT: Hi guys,

After doing all that you guys recommended to me, I have come to the conclusion that the second option is the best.

  1. Create the element
  2. Set all sorts of properties of the element in question
  3. Append

JSperf tests:

6
  • Step 3 in the first option doesn't work. You cant reference or select an element by ID if its not in the DOM. Commented Apr 29, 2014 at 22:56
  • Ah yes my bad! Editting it now! Commented Apr 29, 2014 at 22:57
  • jsperf.com and test yourself. Commented Apr 29, 2014 at 22:59
  • 2
    why you would reference the element again via a query selector. when you create it, you have already the reference !?! Commented Apr 29, 2014 at 23:00
  • @timaschew Performance maybe? Commented Apr 29, 2014 at 23:57

2 Answers 2

1

I would use DocumentFragment like this

var element= document.createDocumentFragment();

then do eveything you need with the element, and then append it to the DOM.

from https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Consequently, using document fragments often results in better performance.

Sign up to request clarification or add additional context in comments.

3 Comments

when I run the test via the button, this is my result: dropbox.com/s/s7ktc1jk11pvqxh/… but the chart at the bottom shows something different, jsperf seems to be broken kind of
well when i look at my task manager since i dont really own a benckmark program document fragment DOES use a tad bit less memory but its not faster in all the tests i have done appreciate the screenshot!
0

I would do as follows:

  1. Create element (maybe set attributes)
  2. Append element
  3. Set attributes, append children to element and anything else you want to do.

2 Comments

and what are your reasons for this order?
@timaschew Because appending children to elements before they are in the dom can get messy. Usually its only a problem with iframes, but its better I believe to use templating or append an element before you add more to it.

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.