Existe-t-il un moyen de convertir la chaîne de balisage en objet nœud en JavaScript? En fait, je cherche le sous-programme pour:
document.getElementById("divOne").innerHTML += "<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"
quelque chose comme
document.getElementById("divOne").appendChild(document.createNodeFromString("<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"))
En utilisant createNodeFromString, créez plutôt l'élément de table, puis ajoutez ses éléments enfants puis attachez leurs attributs et valeurs respectifs!
Il n'existe pas de fonction de navigation croisée existante pour cela. La méthode suivante peut être utilisée pour obtenir l'effet désiré (en utilisant un DocumentFragment
pour une performance optimisée, sur la base de cette réponse ):
function appendStringAsNodes(element, html) { var frag = document.createDocumentFragment(), tmp = document.createElement('body'), child; tmp.innerHTML = html; // Append elements in a loop to a DocumentFragment, so that the browser does // not re-render the document for each node while (child = tmp.firstChild) { frag.appendChild(child); } element.appendChild(frag); // Now, append all elements at once frag = tmp = null; }
Utilisation (indication de la lisibilité):
appendStringAsNodes( document.getElementById("divOne"), "<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>" );
Oui, tu peux faire ça.
var myNewTable = document.createElement("table"); myNewTable.innerHTML = "<tbody><tr><td><input type='text' value='0' /></td></tr></tbody>" document.getElementById("divOne").appendChild(myNewTable);