Importing / Changing HTML content (after ES6 update)

521 Views Asked by At

I have been trying to dynamically change the content of my HTML page by importing external HTML-files. I found a way to do this using HTML imports but if I have understood it correctly this feature is going to become obsolete in because of the ES6 update. From what I've manage to found online there could maybe be an alternative way to do this using javascript modules but I can't find anything concrete.

I want to be to change a big part of the page (a window containing a form becoming a window showcasing user statistics) so it doesn't seem smart to use .innerHTML in javascript. Does anyone have any good ideas on how to import html files or dynamically change the content of the page ? (using javascript, node, etc)

Any help much appreciated :)

1

There are 1 best solutions below

1
Tino T. On

I'm a bit late and the answer has already been linked to in the comments of this question, but here i go anyways.

You should be able to use Ajax to get the html file contents. (As a string) With the content of the html file you should be able to parse it to a htmlDoc in JS (like the global document from document.getElement etc) using the DOMParser class.

https://developer.mozilla.org/en-US/docs/Web/API/DOMParser

https://codepen.io/Deefoozy/pen/PeYWge

After parsing the html into a htmlDocument you should be able to get the body through the result using .getElement or .body.children. The result of this should be a simple domNode which you can append to another domNode.