When should one use [removed] and when [removed] in JavaScript

后端 未结 3 2132
孤独总比滥情好
孤独总比滥情好 2020-12-05 20:05

Is there a general rule, when one should use document.write to change the website content and when to use .innerHTML?

So far my rules were:

3条回答
  •  不知归路
    2020-12-05 20:36

    innerHTML can be used to change the contents of the DOM by string munging. So if you wanted to add a paragraph with some text at the end of a selected element you could so something like

    document.getElementById( 'some-id' ).innerHTML += '

    here is some text

    '

    Though I'd suggest using as much DOM manipulation specific API as possible (e.g. document.createElement, document.createDocumentFragment, .appendChild, etc.). But that's just my preference.

    The only time I've seen applicable use of document.write is in the HTML5 Boilerplate (look at how it checks if jQuery was loaded properly). Other than that, I would stay away from it.

提交回复
热议问题