Búsqueda de sitios web

javascript - Añadir cadena HTML al DOM


Cómo anexar una cadena HTML como

var str = '<p>Just some <span>text</span> here</p>';

al <div> con el id test?

(Por cierto, div.innerHTML += str; no es aceptable.)

Respuesta #1

Usa insertAdjacentHTML, que es compatible con todos los navegadores actuales:

div.insertAdjacentHTML( 'beforeend', str );

El parámetro de posición beforeend se agregará dentro del elemento, después de su último hijo.

Demostración en vivo: http://jsfiddle.net/euQ5n/

Respuesta #2

Rendimiento

AppendChild (E) es más de 2 veces más rápido que otras soluciones en Chrome y Safari, insertAdjacentHTML(F) es el más rápido en Firefox. El innerHTML= (B) (no confundir con += (A)) es la segunda solución rápida en todos los navegadores y es mucho más práctico que E y F.

Detalles

Configurar entorno (10.07.2019) MacOs High Sierra 10.13.4 en Chrome 75.0.3770 (64 bits), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64 bits)

  • en Chrome E (140k operaciones por segundo) es el más rápido, B (47k) y F (46k) son segundos, A (332) es el más lento
  • en Firefox F (94k) es el más rápido, luego B (80k), D (73k), E (64k), C (21k) el más lento es A (466)
  • en Safari E(207k) es el más rápido, luego B(89k), F(88k), D(83k), C(25k), el más lento es A(509)

Puedes reproducir la prueba en tu máquina aquí

function A() {    
  container.innerHTML += '<p>A: Just some <span>text</span> here</p>';
}

function B() {    
  container.innerHTML = '<p>B: Just some <span>text</span> here</p>';
}

function C() {    
  $('#container').append('<p>C: Just some <span>text</span> here</p>');
}

function D() {
  var p = document.createElement("p");
  p.innerHTML = 'D: Just some <span>text</span> here';
  container.appendChild(p);
}

function E() {    
  var p = document.createElement("p");
  var s = document.createElement("span"); 
  s.appendChild( document.createTextNode("text ") );
  p.appendChild( document.createTextNode("E: Just some ") );
  p.appendChild( s );
  p.appendChild( document.createTextNode(" here") );
  container.appendChild(p);
}

function F() {    
  container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');
}

A();
B();
C();
D();
E();
F();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This snippet only for show code used in test (in jsperf.com) - it not perform test itself. 
<div id="container"></div>

Respuesta #3

¿Es esto aceptable?

var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);

jsFiddle.

Pero la respuesta de Neil es una mejor solución.

Respuesta #4

La idea es usar innerHTML en un elemento intermedio y luego mover todos sus nodos hijos a donde realmente los quieres mediante appendChild.

var target = document.getElementById('test');
var str = '<p>Just some <span>text</span> here</p>';

var temp = document.createElement('div');
temp.innerHTML = str;
while (temp.firstChild) {
  target.appendChild(temp.firstChild);
}

Esto evita eliminar cualquier manejador de eventos en div#test, pero todavía te permite agregar una cadena de HTML.

Artículos relacionados