Should you add HTML to the DOM using innerHTML or by creating new elements one by one?

前端 未结 3 1737
暖寄归人
暖寄归人 2020-12-08 16:17

There are two methods to add HTML-code to the DOM and I don\'t know what is the best way to do it.

First method

The first way is the easy on

相关标签:
3条回答
  • 2020-12-08 16:49

    I point to an outdated article for purposes of people testing this for themselves. The DOM methods actually beat out the innerHTML on all of my machines so that is what I prefer. However, at the time of the article innerHTML was faster on avg. Currently the difference can only be seen in huge datasets drastically.

    0 讨论(0)
  • 2020-12-08 17:02

    Actually, neither methods use innerHTML, in both cases jQuery converts the HTML to DOM nodes. From jquery-1.3.2.js:

    // If a single string is passed in and it's a single tag
    // just do a createElement and skip the rest
    if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
        var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
        if ( match )
            return [ context.createElement( match[1] ) ];
    }
    
    // ... some more code (shortened so nobody falls asleep) ...
    
    // Convert html string into DOM nodes
    if ( typeof elem === "string" ) {
        // Fix "XHTML"-style tags in all browsers
        elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
            return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
                all :
                front + "></" + tag + ">";
        });
        // etc...
    }
    

    Generally speaking, using innerHTML is slower than manipulating the DOM, because it invokes the HTML parser (which will parse the HTML into the DOM anyway).

    0 讨论(0)
  • 2020-12-08 17:05

    If I am going to re-use the div later in the code, I'll build it and put it in a var, usually with a $ prefix so I know it's a jQuery object. If it's a one-off thing I'll just do a:

     $('body').append(the stuff)
    
    0 讨论(0)
提交回复
热议问题