I am being passed html as a string. My goal is to create a new document from the html that has all the appropriate nodes so that I can do things like call doc.getElementsByTagName on the doc I create and have it work as expected. An example of my code is here.
var doc = window.document.implementation.createDocument
('http://www.w3.org/1999/xhtml', 'html', null);
doc.getElementsByTagName('html')[0].innerHTML =
'<head><script>somejs</script>' +
'<script>var x = 5; var y = 2; var foo = x + y;</script>' +
'</head><body></body>';
var scripts = doc.getElementsByTagName('script');
console.log(scripts[0] + " code = " + scripts[0].innerHTML);
I am having the following issues:
- If something inside a script tag contains a character like < (eg in the example above in the "var foo = x + y;" statement change the + to a < symbol), I get an INVALID_STATE_ERR: DOM Exception 11.
- Even if nothing inside the script tag uses such characters, when I run the above I get the output "[object Element] code =undefined"
So my questions are:
A. How do I handle characters such as < that give DOM Exception 11 when I try to use them in whatever I am setting the innerHTML to B. How do I make the document properly parse the script tags and put their code into their innerHTML attribute so that I can later read it.
EDIT: As Ryan P pointed out this code actually works in FF. So if anyone could help me get it working in chrome that would be much appreciated!