3

I have a empty div identified by "parent". I want to put an p element inside of it. There are two methods:

Firts method:

parent.innerHTML = "";
parent.innerHTML = "<p>My dummy text</p>";

Second method:

var myP = document.createElement('p');
var myText = document.createTextNode("My dummy text here");
myP.appendChild(myText);
parent.appendChild(myP);

Is there a difference between the two methods when it comes to the good practices?

Thanks!

3
  • 3
    Setting innerHTML replaces existing content. It doesn't append. These two code snippets have different effects. Commented Oct 31, 2011 at 16:43
  • Sorry about that. I edited the code. Commented Oct 31, 2011 at 16:45
  • Your edit didn't change the way the first code snippet works. Commented Oct 31, 2011 at 16:46

7 Answers 7

3

When you're intending to add plain text (no event listeners), no complex attribute values, innerHTML is usually a good option.

If the text doesn't contain any HTML tags, textContent or innerText (IE) is a better choice, because setting these properties won't cause the string to be parsed as HTML.

Tons of document.createElement and appendChild are usually slower than setting the innerHTML property, especially when you're comparing 1000x append-to-body vs 1x .innerHTML.

It's recommended to use appendChild when you want to extend an element whose content is unknown (it may contain event listeners, or user-modified input elements).

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

1 Comment

Why would you append thousands of times :\. You'd append to a document fragment and append the document fragment once.
2

The 1st option can remove any event listeners you might have on that peice of the DOM
Whereas the second option will not.

Better to go with option #2.

1 Comment

if the question was intact when you posted your answer your wrong about 1st option can remove any event listeners
1

Here some differences:

BAD

  • It's not a standard. It's a proprietary property that Microsoft introduced (along with the less popular outerHTML) that the other browser makers picked up.
  • Since it's not a standard, it's not supposed to work under the application/xhtml+xml MIME type that XHTML documents are supposed to be served under. (Firefox 1.5 changed this by allowing it for some reason)
  • InnerHTML is a string. The DOM is not a string, it's a hierarchal object structure.
  • It makes for some nearly illegible code in a lot of instances, with escaped quotes and plus signs all over the place appending data to the string.

GOOD

  • It's faster than DOM methods. By a lot.

  • It's less verbose than DOM methods.

  • It allows you to take arbitrary chunks of markup and drop them into a document without having to parse them.

2 Comments

It's not faster then DOM methods. That's a myth.
innerHTML is a standard, now. It's in HTML5: html5.org/specs/dom-parsing.html#innerhtml
1

The first approach can introduce XSS holes, if you are not careful. Using it with constant strings like in your example is safe, but consider the following:

parent.innerHtml = "<p>" + document.getElementById('userInput').value + "</p>";

You've just injected user input directly into your DOM. If that input contains a script tag, then you've just been XSS'd. This is a contrived example, but you can imagine how you might accidentally generate a string from unescaped user input on the server side and write that into your DOM.

Comments

1

.innerHTML is the devil. We do not use it.

We use the DOM methods because we shouldn't be hacking around with in-line pieces of JavaScript.

The only valid use case for .innerHTML are cross browser compliance hacks and templating engines.

If your not doing either of those then your supposed to be using DOM4.

3 Comments

You and I have discussed this privately, but although I sympathize with the general sentiment, I disagree with the absoluteness of your position on this, on the basis of readability. For simple cases, I'd prefer el.innerHTML = "<p>Cheese is <b>great</b><p>" over the equivalent with three appendChild()s, two document.createElement()s and one document.createTextNode().
@TimDown Still violates seperations of concerns :\ You wouldn't advocate <input onclick="changeinput()" />. Also your example is contrived. I can't think of solid real world use-cases where you want code that looks like that in your javascript. I think it's very rare occurance where you can justify inline html in your javascript but cant justify templating engines. And as mentioned templating engines that do .innerHTML for you are cool. As an aside based on our discussion I have made exceptions for browser hacks and templating.
Good points. I can't think when I last used innerHTML except for a quick prototype or for debugging, so I probably agree with you really.
-1

From GWT UiBinder doc:

"Browsers are better at building DOM structures by cramming big strings of HTML into innerHTML attributes than by a bunch of API calls."

I think they know what they are talking about in this case.

So apart from the fact that it does not append as Rob Mayoff mentioned in the comment it's probably faster to go with innerHTML especially for less trivial cases.

2 Comments

That's simply not true. There is very little difference.
It's particularly true for IE that some of us still has to support but it's also true to some extent in other browsers. quirksmode.org/dom/innerhtml.html
-2

The only difference I see is when you're using inputs. Some browsers don't recognize that new inputs were added to a form and then, when submitted, don't include those inputs.

When using appendChild this problem does not occur. So, it is a good practice to manipulate DOM and append properly.

If you think it is too much work, create each element and append it, you may consider use some framework to make it faster. jQuery, for example, allows you to use $(parent).html("<p>My dummy text here</p>") and automatically create nodes for you.

1 Comment

"framework to make it faster". No. jQuery is slow as hell, if he cares about performance he avoids jQuery

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.