Javascript innerHTML vs outerHTML

后端 未结 3 425
忘掉有多难
忘掉有多难 2021-01-03 23:24

I have the following javascript:

// create a new article tag
var elem = document.createElement(\'article\');

// append the article to the comments list
docu         


        
3条回答
  •  盖世英雄少女心
    2021-01-03 23:47

    I'd say both are probably not what you want, use textContent or else whatever property handles the text for the element.

    elem.textContent = "This is the comment";
    elem.classList.add("comment"); 
    

    innerHTML parses content as HTML and completely destroys the element and recreates it, it also destroys any event handlers, etc that might be registered for the element. With outerHTML the element set will still hold a reference to the original element (if any).

    So both have possible unintended side-effects vs the correct property to set text content.

提交回复
热议问题