12

Possible Duplicate:
JavaScript: Is it better to use innerHTML or (lots of) createElement calls to add a complex div structure?

What should I use instead of .innerHTML? All advice is appreciated.

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253

6 Answers6

21

The correct answer is that in certain situations you should use innerHTML, and in other situations you should use appendChild. Here's when to use innerHTML or appendChild:

  • Use innerHTML when you're setting text inside of an HTML tag like an anchor tag, paragraph tag, span, div, or textarea.

  • Use appendChild() If you're trying to add new DOM elements inside of another DOM element.

Eric Rowell
  • 5,191
  • 23
  • 22
  • *"The correct answer is that in certain situations you should use innerHTML..."* I don't think it's correct to say that you *"should"* use `innerHTML`, but it certainly is an option. – user113716 Sep 19 '11 at 20:23
  • 3
    I actually do mean to say "should use". String concatenation is more computationally expensive than working with DOM objects directly. Therefore, it's good practice to use appendChild() to add new DOM objects, and it's good practice to use innerHTML when you're actually wanting to insert text. – Eric Rowell Sep 19 '11 at 21:17
  • 4
    Yes, but saying it's *"good practice"* to use `.innerHTML` to insert text is different than saying you *"should"* use `.innerHTML` for that. There's nothing wrong with using `document.createTextNode()` along with `.appendChild()` if you want some text inserted. But I do agree that it is good practice to use `appendChild()` and similar for DOM elements. – user113716 Sep 19 '11 at 21:22
  • 3
    Actually, if you're just adding text, use `innerText`. – LetMyPeopleCode Jan 23 '15 at 05:32
  • @YiddishNinja `innerText` is non-standard, however it is fairly widely supported: http://caniuse.com/#search=innerText – leftclickben Jan 16 '16 at 10:47
  • The more standards-compliant way to insert text is to append a text node. The DOM API unfortunately makes this needlessly terse - why couldn't they have made `$element->appendChild('This text');` work instead of needing something like `$element->appendChild($doc->createTextNode('This text`));`? At any rate, it avoids the problems of needing to escape '<' and '&' for innerHTML, and that innerText is non-standard (and treats whitespace weirdly). – thomasrutter Jun 27 '16 at 06:09
  • Consider also that string concatenation to build HTML is also more error prone. – Iharob Al Asimi Sep 14 '16 at 19:25
  • Actually, @thomasrutter, check out [element.append()](https://developer.mozilla.org/en-US/docs/Web/API/Element/append). It accepts either a _node object_ or a _string_ as input, and can accept multiple nodes/string to append with one call. – David Michael Gregg May 02 '22 at 04:53
  • @DavidMichaelGregg those new methods are quite useful - if only DOM had had that from the start we wouldn't have had to fudge around with any of this. Note this question/answer harks from a time before those. – thomasrutter May 03 '22 at 03:25
  • @thomasrutter For sure! It has been around _just_ long enough in the biggest browsers now that I recently started teaching it as the default way to add things to the DOM – along with `prepend()`, `after()`, and `before()` in vanilla JS. – David Michael Gregg May 06 '22 at 00:19
3

You can use W3C compliant methods, like:

user113716
  • 318,772
  • 63
  • 451
  • 440
  • 2
    Actually `innerHTML` is perfectly W3C compliant as per the actual W3C docs here: https://www.w3.org/TR/DOM-Parsing/ "DOMParser, XMLSerializer, innerHTML, and similar APIs" and as per here, it is supported in all browsers including IE8+ http://caniuse.com/#search=innerHTML – leftclickben Jan 16 '16 at 10:46
  • `innerHTML` is fine in the cases that the answer specifies. – jonlink Dec 26 '17 at 19:52
  • `.innerHTML` was indeed non-standard back in 2011. @jonlink: It can only be used consistently in place of `.appendChild()`, but to do that you need to use `+= new_data`, which can introduce bugs to your code. –  Dec 27 '17 at 19:30
  • I realize this answer is old, but since SO is a living doc it is worth mentioning. Just about everything was non-standard in 2011 :) In any case I was actually referring to using innerHTML to fill or replace contents as a whole, so `+= new data` would be unnecessary. That said, it isn't performant. For example if you want to empty the [innerHTML a while loop is better](https://coderwall.com/p/nygghw/don-t-use-innerhtml-to-empty-dom-elements) – jonlink Dec 28 '17 at 17:26
  • EDIT: seems innerHTML was standard in 2011 ([source](https://www.quora.com/Why-is-innerHTML-not-standard-yet)). Maybe you were thinking of innerText? – jonlink Dec 28 '17 at 17:34
3

Without any context, there is only one rule: there are no rules.

There are no situations in programming where one follows some "rule" blindly, regardless of the context. If innerHTML were inherently eval, I mean evil, it wouldn't be in the language specification to begin with!

The alternatives to using innerHTML vary depending on what you are trying to do, what (if any) javascript libraries you have, and what (if any) browsers you are targeting.

When you're creating a new section of HTML, you can use document.createElement (docs) to make each element, using appendChild and the like to add elements to one another. If you're changing the text of an element from "blue" to "red", you'd use innerHTML to accomplish that (assuming you don't use any of the popular javascript frameworks).

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
1

When practical, it's better to create the DOM objects yourself and add them to the DOM tree—performance will be better. For complex elements, it's probably better to use innerHTML or otherwise you'll have unmaintainable code.

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
0

Just like the answer here, "use an API". jQuery is way better at this than you and its extremely easy to use, so just use that.

Looks like no one wants to click through so i'll quote the answer.

Neither. Use a library like jQuery, Prototype, Dojo or mooTools because both of these methods are fraught with trouble:

The writers of the major javascript libraries have spent a lot of time and have entire bug tracking systems to make sure that when you call their DOM modifying tools they actually work.

If you're writing a library to compete with the above tools (and good luck to you if you are), then I'd choose the method based on performance, and innerHTML has always won out in the past, and since innerHTML is a native method, it's a safe bet it will remain the fastest.

The key takeaway here is that DOM manipulation done right is a sufficiently complex task to really make one look strongly at using a library to abstract away the headaches you may encounter.

Community
  • 1
  • 1
Allen Rice
  • 19,068
  • 14
  • 83
  • 115
-1

You should exchange objects (JSON or XML) instead of pure HTML between AJAX requests. Then, you need a presentation logic on your client to handle the data (JSON or XML) and update the DOM accordingly.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Fabrizio D'Ammassa
  • 4,729
  • 25
  • 32