javascriptjquery

Why does this function mutate innerHTML of a div element and extract its first child to parse HTML if you can just use jQuery to do the same?


I just encountered with this code:

foo = (function() {
    var div = document.createElement('div');
    return function(html) {
        div.innerHTML = html;
        var item = div.firstChild;
        div.removeChild(item);
        return item;
    };
})();

and it is being used like this:

var element=foo('<table><tr><td></td></tr><table>');

I noticed that the above return the JavaScript element with it. I wonder can't it be done only with this -

var element=$('<table><tr><td></td></tr><table>')[0];

What exactly the original JS function is doing actually? What is the benefit of taking this var div = document.createElement('div'); outside the return statement ?


Solution

  • It creates a div document element once and caches it in the scope of the function for future execution of this method so it doesn't have to be created every time the function is called.

    It's a micro optimization pattern called Lazy initialization - you can read more about it here http://en.wikipedia.org/wiki/Lazy_initialization

    To answer your second question - yes what you showed in jQuery would give you exactly the same output.