0

My research didn't prove very succsessful since I don't really know how to explain it when it is not by example.

Consider the following:

You have a webpage. One div of the webpage will by dynamic, meaning that it will load different things, like tables, paragraphs, ect ect.

Let's have set the div's id to 'main' and have this for conveneance:

var main = document.getElementById("main");

Now, this is the tricky part: When you want to change it's children you have 2 options:

1) Remove all children; create a variable in javascript for each new element; style it; set inner html; append. Example:

//Consider that the children have already be cleared
     var p = document.createElement("p");
        p.innerHTML = "Hello World";
        p.className = "style";
        main.appendChild(p);

    var p2 = document.createElement("p");
    p2.innerHTML = "Goodbye world!";
    p2.className = "byeStyle";
    main.appendChild(p);

2) Set the inner html of the variable to, basically what you want it to be. Example2:

 main.innerHTML = '<p class="style">Hello world!</p>' +
                    '<p class="byeStyle">Goodbye world!</p>';

Both will work fine. Which is preferred and which has better performance?

12
  • 1
    strictly speaking for a fair comparison your first block should be using document.createTextNode to make the elements' contents. Commented Jul 24, 2013 at 8:35
  • 3
    Assigning to innerHTML is usually much faster. Browsers have optimized HTML parsers, since that's what they do 99% of the time. Commented Jul 24, 2013 at 8:35
  • If you want to see the difference, make a benchmark at jsperf.com. Commented Jul 24, 2013 at 8:36
  • @Barmar I've seen JS perf benchmarks that suggest there's little difference on modern browsers. Commented Jul 24, 2013 at 8:36
  • 1
    look at jsperf.com/node-creation-html-vs-dom Commented Jul 24, 2013 at 8:38

1 Answer 1

1

In general, it doesn't matter unless you're doing this over and over in a tight loop.

Perceived wisdom is that using .innerHTML is faster, however on modern browsers that is not necessarily the case.

See e.g. http://jsperf.com/node-creation-html-vs-dom/2, where using raw DOM access on Chrome version 28 is 5x faster than using .innerHTML.

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

2 Comments

So, when the change is made only when, for example pressing a button, the difference is irrelevant ?
@Bloodcount pretty much, yes, unless you're going to be updating hundreds of nodes. If it's just a couple of nodes, just go for cleanest code.

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.