Returning contents of template tag as string

2019-08-11 15:08发布

I was wondering if there was a way of getting the contents of the elements within a template tag and returning it as a string? At the moment it seems like it is returning something along the lines on [object document fragment] but want just the html content inside.

function CreateWidget(widget) {
    //Check if browser supports templates
    if ('content' in document.createElement('template')) {
        //Grab the template's content and assign it to a variable so we only have the gut of the template
        var widgetContent = document.querySelector('#panel-template').content //('#panel-template').get(1).setAttribute('id', widget.WidgetCode);
        widgetContent.querySelector('#chart').setAttribute('id', widget.WidgetCode);

        //get the overlay toolbar
        var widgetOverlay = widgetContent.querySelector('.overlayed');
        widgetOverlay.setAttribute('data-render', widget.WidgetCode);
        widgetOverlay.setAttribute('data-chartType', widget.chartType);
        widgetOverlay.setAttribute('data-devID', widget.deviceID);
        widgetOverlay.setAttribute('data-metricType', widget.metricType);
        widgetOverlay.setAttribute('data-title', widget.WidgetName);

        var el = document.importNode(widgetContent, true);
        alert(el);   
    }
}

1条回答
疯言疯语
2楼-- · 2019-08-11 15:12

If all you want is the HTML as a string, you can get that with just the usual .innerHTML; like this:

document.querySelector("template").innerHTML

If you instead want the textContent, you can get that from .content.textContent; like this:

document.querySelector("template").content.textContent

If you want to actually iterate over the template child nodes or do much else of anything with its content, you need to use that .content property, which returns a DocumentFragment.

From that you have children, firstElementChild, lastElementChild, childElementCount, and find(), findAll(), querySelector(), querySelectorAll(), getElementById; at least eventually—other than the query* methods and getElementById(), I’m not sure if IE/Edge and Safari support most of it yet (ca. 2015-10). And I think nobody yet supports find()/findAll().

查看更多
登录 后发表回答