HTML-Dokument aus Code-Schnipsel erstellen
von Sven Mintel
am 07.09.10 um 16:15 (1378 Hits)
Nützlich beim Einsatz von AJAX, wenn man entweder kein gültiges XML-Dokument geliefert bekommt, und responseXML somit leer ist, oder man aber ein gültiges XML-Dokument geliefert bekommt, dort aber auch getElementById() & getElementsByName() oder sonstige HTML-eigene Dinge verwenden möchte, die in XML-Dokumenten nicht verfügbar sind:Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37<script type="text/javascript"> <!-- function loadHTML(strHTML) { var doc=null; if(document.all && !window.opera)//IE { doc=document.createDocumentFragment(); doc.appendChild(doc.createElement('root')); doc.firstChild.innerHTML=strHTML; } else { if(document.implementation) { if(window.opera || typeof window.mozInnerScreenX!='undefined')//Opera + FF { doc=document.implementation.createDocument ('http://www.w3.org/1999/xhtml', 'root', null); doc.documentElement.innerHTML=strHTML } else//chrome+safari { doc=document.implementation.createDocument ('http://www.w3.org/1999/xhtml', '', null); var root=doc.createElement('root'); root.innerHTML=strHTML; doc.appendChild(root); } } } return doc; } //Kurzer test alert(loadHTML('<b><i id="elementID">Es geht</i></b>').getElementById('elementID').innerHTML); //--> </script>
Getestet in
- FF3.6.8
- Opera9.5
- Win-Safari 5.0.1
- Chrome5.0
- IE6-8
Auslöser dafür war dieses Thema:
http://www.tutorials.de/javascript-a...behandeln.html






