views:

1278

answers:

3

Is there any way to create or recreate a javascript document Object by calling a function. Something like

<script type="javascript/text">
  var document = createDocument("some html");
</script>

I want to do this so I can solve the issue in this question client side xslt with javascript in firefox

+1  A: 

You could try using document.implementation.createDocument. Once you have your document, you can use the innerHTML property to set HTML for it. If you want that wrapped in a neat little package you can do something like this:

function createDocument(html) {
    var doc = document.implementation.createDocument ('http://www.w3.org/1999/xhtml', 'html',  null);
    doc.documentElement.innerHTML = html;
    return doc;
}

And the you'd use the function like this:

var doc = createDocument("<body><span>Hello StackOverflow.com!</span></body>");

Let me know if this is what you were looking for.

Dan Herbert
+1  A: 

This works in Firefox:

document.implementation.createDocument(null, "rootElement", null)

Note that it gives you a XMLDocument, rather than a HTMLDocument (like document itself).

Matthew Flaschen
A: 

Don't have enough rep to post a comment so I am adding a answer that is not really an answer...

Thanks for the responses. Dan, that is pretty close to what I was looking for. This still seems to create an XMLdocument but I really need an html document. Can I turn one into the other? I need to be able to access things like document.forms and document.anchors with the document I create.

Also, can I replace/redefine the document used in document.write?

Again, thanks for the help.

Also, what would be the IE equivalent of this? Is this something that would have to be done per browser?