Puede que se de el caso de que halles algún error con tu código o trabajo, recuerda probar siempre en un ambiente de testing antes añadir el código al proyecto final.
Solución:
innerHTML
y document.write
no son realmente métodos comparables para cambiar/insertar contenido dinámicamente, ya que su uso es diferente y para diferentes propósitos.
document.write
debe estar vinculado a casos de uso específicos. Cuando se ha cargado una página y el DOM está Listo ya no puedes usar ese método. Es por eso que generalmente se usa más en declaraciones condicionales en las que puede usarlo para cargar sincrónicamente un archivo javascript externo (bibliotecas javascript), incluyendo blocks (e.g. when you load jQuery from the CDN in
HTML5 Boilerplate
).
What you read about this method and XHTML is true when the page is served along with the application/xhtml+xml
mime type: From w3.org
document.write (like document.writeln) does not work in XHTML documents (you'll get a "Operation is not supported" (NS_ERROR_DOM_NOT_SUPPORTED_ERR) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type
Another difference between these approaches is related on insertion node: when you use .innerHTML
method you can choose where to append the content, while using document.write the insertion node is always the part of document in which this method was used.
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
,
, 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.
1) document.write() puts the contents directly to the browser where the user can see it.
this method writes HTML expressions or JavaScript code to a document.
The below example will just print ‘Hello World’ into the document
2) document.innerHTML cambia el contenido interno de un elemento
Cambia el contenido existente de un elemento.
El siguiente código cambiará el contenido de la etiqueta p
Click me to change my HTML content or my inner HTML
podría usar document.write() sin ningún HTML conectado, pero si ya tiene HTML que desea cambiar, entonces document.innerHTML sería la opción obvia.