Search code examples
javascripthtmljquerydominnerhtml

HTML Document Used as a String in Javascript


I am using JQuery to create "applications" for my website. I don't know the proper syntax for pulling an html document into a string, so that the application button opens a window with the html document inside.

I'm trying to rewrite this string variable within a function:

   $('.openbuttonapp').dblclick(function () {
            var $objWindow = $('<div class="window"> Put me in, Coach! </div>');

to look something like this:

        var entireDocumentHTMLAsAString = document.documentElement.innerHTML;

        $('.openbuttonapp').dblclick(function () {
            var $objWindow = $(entireDocumentHTMLAsAString);

entireDocumentHTMLAsAString is intended to be a .html within my folders. I need tips to use this syntax properly, so that I can diplsay the html documents that I need.

See full project on Github: https://github.com/sosophia10/TimeCapsule (see js/experience.js)


Solution

  • You can simply fetch() the contents of an HTML source file. In the following example I used a publicly available HTML source:

    const url="https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=html";
    
    fetch(url).then(r=>r.text()).then(html=>document.querySelector("div").innerHTML=html)
    <div></div>