1

Is there any way to create a javascript document Object by calling a function? Something like this:

<script type="javascript/text">
  var myDoc = createDocument("example.html");
</script>

I want to be able to create and manipulate a DOM from a string, 'example.com'.

starball
  • 20,030
  • 7
  • 43
  • 238
Amin
  • 13
  • 2
  • is `"example.html"` the local file? – RomanPerekhrest Mar 03 '17 at 21:31
  • "example.html" is in a variable within the javascript program. – Amin Mar 03 '17 at 21:33
  • Could you be more specific in your question? – Omri Luzon Mar 03 '17 at 21:38
  • Is `example.html` an `html` `document`? – guest271314 Mar 03 '17 at 21:39
  • Yes it is an html document. – Amin Mar 03 '17 at 21:44
  • You can use `` element with `"import"` set at `rel` attribute to get resource as a `document` within `html` `document`. See [Is there a way to know if a link/script is still pending or has it failed](http://stackoverflow.com/questions/39824927/is-there-a-way-to-know-if-a-link-script-is-still-pending-or-has-it-failed/39908873#39908873), [Include file In HTML by JavaScript or jquery dynamically](http://stackoverflow.com/questions/42586310/include-file-in-html-by-javascript-or-jquery-dynamically/42586440?s=6|0.0545#42586440) – guest271314 Mar 03 '17 at 22:17

1 Answers1

0

Initially you need to get html through AJAX request after use DOMParser.

var parser = new DOMParser();
var doc = parser.parseFromString("<html_string>", "text/html");

OR

var doctype = document.implementation.createDocumentType(
    'html',
    '-//W3C//DTD XHTML 1.0 Strict//EN',
    'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
);

var dom = document.implementation.createDocument(
    'http://www.w3.org/1999/xhtml',
    'html',
    doctype
);

 // assign the body of your page, after you can use dom variable.
dom.documentElement.innerHTML = '<head></head><body></body>';
artamonovdev
  • 2,260
  • 1
  • 29
  • 33