2012-04-25 6 views
35

Necesito poder agregar elementos a una página con una cadena de texto en bruto de HTML, incluyendo cualquier cantidad de etiquetas, atributos, etc. Idealmente, me gustaría poder hacer algo así como con cualquier cadena arbitraria de html bien formado;Agregue elementos al DOM dado HTML de texto sin formato usando solo JavaScript puro (no jQuery)

var theElement = document.createElement("<h1 id='title'>Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>"); 

document.getElementById("body").appendChild(theElement); 

Obviamente, eso no funciona, estoy buscando buenas maneras de lograr el mismo resultado. Me gustaría evitar analizar el HTML si es posible. Tengo muchas restricciones sobre las herramientas que puedo usar, no jQuery o fuera incluye y debe ser compatible con navegador cruzado y compatible con IE6. Cualquier ayuda sería enorme.

Respuesta

54

prueba de asignar a la innerHTML property de un elemento anónimo y añadiendo cada uno de sus children.

function appendHtml(el, str) { 
    var div = document.createElement('div'); 
    div.innerHTML = str; 
    while (div.children.length > 0) { 
    el.appendChild(div.children[0]); 
    } 
} 
var html = '<h1 id="title">Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>'; 
appendHtml(document.body, html); // "body" has two more children - h1 and span. 
+2

Debe usar un [DocumentFragment] (http://ejohn.org/blog/dom-documentfragments/) en lugar de un div; será más rápido y mucho más fácil mover los nodos secundarios. ** Editar **: Scratch ese comentario, ya que no puede establecer 'innerHTML' de un DocumentFragment. – Phrogz

+0

la edición para cambiar al ciclo while solucionó el problema con el ciclo for utilizando un índice, ya que appendChild elimina realmente el elemento del div para agregarlo al cuerpo. La clonación del nodo hijo es una forma menos elegante de hacer esto también. – kirps

+0

@kirps: sí, finalmente probé ese código de muestra y descubrí el comportamiento extraño de "appendChild" y su efecto sobre el atributo "secundario" del elemento primario que lo contiene. – maerics

4

Puede obtener el elementoId del elemento bajo el cual desea insertar el HTML y usar innerHTML para agregar el html.

document.getElementById("body").innerHTML = "<h1 id='title'>Some Title</h1><span>test</span>"; 
+1

No estoy seguro acerca de 'document.getElementById (" body ")' que en mi opinión sería bastante ... NULL! ;-). Use 'document.getElementsByTagName ('body') [0]' –

11
var el = document.createElement("h1") 
el.id="title"; 
el.innerHTML = "Some title"; 
document.body.appendChild(el); 

var el2 = document.createElement("span") 
el2.style.display="block"; 
el2.style.width="100%"; 
el2.innerHTML = "Some arb text"; 
document.body.appendChild(el2); 

Shoud trabajo (violín: http://jsfiddle.net/gWHVy/) solución

1

maerics fijado mi problema de inmediato. Sin embargo, necesitaba hacer un ajuste rápido para hacer lo que necesitaba. Tengo varias secuencias de comandos y hojas de estilo que se cargan al hacer clic. No puedo agregar scripts ni hojas de estilo como objetos reales a la carga posterior del DOM. Si configura innerHTML para decir, document.body, para que contenga la parte <link rel="stylesheet" />, solo imprimirá el texto y el navegador no lo reconocerá como un objeto de enlace. Para solucionar esto, utilicé el siguiente código.

function appendHtml(el, str) { 
    var div = document.createElement('div'); 
    div.innerHTML = str; 
    while (div.children.length > 0) { 
     if (div.children[0].tagName == 'LINK') { 
      // Create an actual link element to append later 
      style = document.createElement('link'); 
      style.href = div.children[0].href; 
      // append your other things like rel, type, etc 
      el.appendChild(style); 
     } 
     el.appendChild(div.children[0]); 
    } 
} 
Cuestiones relacionadas