What is better, appending new elements via DOM functions, or appending strings with HTML tags?

后端 未结 6 1133
无人共我
无人共我 2020-11-29 05:34

I have seen a few different methods to add elements to the DOM. The most prevelent seem to be, for example, either

document.getElementById(\'foo\').innerHTM         


        
6条回答
  •  醉话见心
    2020-11-29 06:06

    I always prefer readability unless the perf difference is extreme. In a one-off case of this, it probably will be a marginal difference.

    In a one-off case like this, setting the innerHTML property will be easiest to read.

    But if you are doing a lot of programmatic content generation in JavaScript, it is cleaner and easier to read and understand the DOM option.

    Example:

    Compare this innerHTML code:

    http://jsfiddle.net/P8m3K/1/

    // Takes input of a value between 1 and 26, inclusive,
    // and converts it to the appropriate character
    function alphaToChar(alpha)
    {
        return String.fromCharCode('a'.charCodeAt() + alpha - 1);
    }
    
    var content = "
      "; for(i = 0; i < 10; ++i) { content += "
    • "; for(j = 1; j <= 26; ++j) { content += "" + alphaToChar(j) + ""; } content += "
    • "; } document.getElementById("foo").innerHTML = content;

    To this DOM code:

    http://jsfiddle.net/q6GB8/1/

    // Takes input of a value between 1 and 26, inclusive,
    // and converts it to the appropriate character
    function alphaToChar(alpha)
    {
        return String.fromCharCode('a'.charCodeAt() + alpha - 1);
    }
    
    var list = document.createElement("ul");
    for(i = 0; i < 10; ++i)
    {
        var item = document.createElement("li");
        for(j = 1; j <= 26; ++j)
        {
            var link = document.createElement("a");
            link.setAttribute("href", alphaToChar(j) + ".html");
            link.innerText = alphaToChar(j);
            item.appendChild(link);
        }
        list.appendChild(item);
    }
    document.getElementById("foo").appendChild(list);
    

    At this level they start to become quite similar length wise.

    But the DOM code will be easier to maintain, and you're a bit less likely to make a typo or mistake that is hard to diagnose, like omitting a closing tag. Either your elements will be in your document, or they won't.

    • With more complicated scenarios (like building treed menus), you'll probably come out ahead with DOM code.
    • With scenarios where you have to append multiple types of content together to build a document with more heterogeneous content, it becomes a slam dunk. You don't have to ensure you call your child append code before calling the parent append code.
    • With scenarios where add, remove, or modify existing static content, DOM will usually win.

    If you start doing complicated DOM modifications (one of the last things I mentioned), you'll definitely want to check out a library built around DOM modifications, like jQuery.

提交回复
热议问题