Create a DOM document from string, without JQuery

后端 未结 9 470
梦如初夏
梦如初夏 2020-12-05 14:12

We\'re looking for ways to create a DOM document in javascript from a string, but without using Jquery. Is there a way to do so? [I would assume so, since J

相关标签:
9条回答
  • 2020-12-05 14:33

    I tried some of the other ways here but there where issues when creating script elements such as Chrome refusing to load the actual .js file pointed to by the src attribute. Below is what works best for me.

    It's up to 3x faster than jQuery and 3.5x faster than using DOMParser, but 2x slower than programmatically creating the element.
    https://www.measurethat.net/Benchmarks/Show/2149/0

    Object.defineProperty(HTMLElement, 'From', { 
        enumerable: false,
        value: (function (document) {
            //https://www.measurethat.net/Benchmarks/Show/2149/0/element-creation-speed
            var rgx = /(\S+)=(["'])(.*?)(?:\2)|(\w+)/g;
            return function CreateElementFromHTML(html) {
                html = html.trim();
                var bodystart = html.indexOf('>') + 1, bodyend = html.lastIndexOf('<');
                var elemStart = html.substr(0, bodystart);
                var innerHTML = html.substr(bodystart, bodyend - bodystart);
                rgx.lastIndex = 0;
                var elem = document.createElement(rgx.exec(elemStart)[4]);
                var match; while ((match = rgx.exec(elemStart))) {
                    if (match[1] === undefined) {
                        elem.setAttribute(match[4], "");
                    } else {
                        elem.setAttribute(match[1], match[3]);
                    }
                }
                elem.innerHTML = innerHTML;
                return elem;
            };
        }(window.document))
    });
    

    Usage Examples:

    HTMLElement.From(`<div id='elem with quotes' title='Here is "double quotes" in single quotes' data-alt="Here is 'single quotes' in double quotes"><span /></div>`);
    HTMLElement.From(`<link id="reddit_css" type="text/css" rel="stylesheet" async href="https://localhost/.js/sites/reddit/zinject.reddit.css">`);
    HTMLElement.From(`<script id="reddit_js" type="text/javascript" async defer src="https://localhost/.js/sites/reddit/zinject.reddit.js"></script>`);
    HTMLElement.From(`<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">`);
    HTMLElement.From(`<div id='Sidebar' class='sidebar' display=""><div class='sb-handle'></div><div class='sb-track'></div></div>`);
    
    0 讨论(0)
  • 2020-12-05 14:37
    fetch("index.html", {  // or any valid URL
        method: "get"
    }).then(function(e) {
        return e.text().then(e => {
            var t = document.implementation.createHTMLDocument("");
            t.open();
            t.write(e);
            t.close();
            return t;
        });
    }).then(e => {
        //  e will contain the document fetched and parsed.
        console.log(e);
    });
    
    0 讨论(0)
  • 2020-12-05 14:42

    I was able to do this by writing the html string on an iframe

    const html = `<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
    </head>
    <body>
    
    </body>
    </html>`
    
    const iframe = document.createElement('iframe')
    iframe.contentDocument.open()
    iframe.contentDocument.write(html)
    iframe.contentDocument.close()
    iframe.addEventListener('load', () => {
      myDocumentObject = iframe.contentDocument
    })
    
    0 讨论(0)
提交回复
热议问题