0

What is the best approach to creating elements in JavaScript? I know about creating element using:

string example:

var div="<div></div>" 

And another way is using

document.CreateElement('div').

Which one is the best method to achieve high performance? Is there is any other way to achieve this?

tckmn
  • 57,719
  • 27
  • 114
  • 156
Raja
  • 489
  • 1
  • 7
  • 11
  • 2
    Your first example doesn't create an element. It's just a string. Your second example is wrong (it's `document.createElement` with a lower-case `c`). – T.J. Crowder Oct 26 '13 at 16:24
  • Hi, Thank you for your reply. Sorry for the mistake in our question. How to create the element in the JavaScript, Is there any other best approach for creating element in JavaScript – Raja Oct 26 '13 at 16:27

2 Answers2

1

There is no single "best" approach, the best thing to do varies with the situation.

You basically have two choices:

  1. Use the DOM methods to create elements (document.createElement('tagName')) and append/insert them into the DOM (appendChild, insertBefore), or

  2. Use innerHTML on an existing element, assigning an HTML string to it; the browser will parse and render the HTML.

It used to be, just a couple of years ago, that innerHTML was a lot faster. But modern versions of browsers have improved the speed of DOM access dramatically, so really it comes down to what works best for the overall task you're performing.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

When you append that div="<div></div>" to your body like I'm sure you meant to do, that works fine but is inefficient.

If you create the element, it creates its own object. The first option using the div var will allocate memory for the string and then again for the object itself and you have to reference it separately anyway. Basically doubling the browser's work.

Deryck
  • 7,608
  • 2
  • 24
  • 43