Create a DOM document from string, without JQuery

后端 未结 9 495
梦如初夏
梦如初夏 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(`
    `); HTMLElement.From(``); HTMLElement.From(``); HTMLElement.From(``); HTMLElement.From(``);

提交回复
热议问题