将模板标签的内容作为字符串返回

Returning contents of template tag as string

我想知道是否有办法获取模板标签中元素的内容并将其作为字符串返回?目前它似乎正在返回 [object document fragment] 上的内容,但只需要里面的 html 内容。

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);   
    }
}

如果您只需要 HTML 作为字符串,您可以使用通常的 .innerHTML:

document.querySelector("template").innerHTML

如果您想要 textContent,可以从 .content.textContent 获得;像这样:

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

如果你想实际遍历 template 子节点或对其内容做很多其他事情,你需要使用 .content 属性,returns一个DocumentFragment.

据此你有 childrenfirstElementChildlastElementChildchildElementCountfind()findAll()querySelector(), querySelectorAll(), getElementById;至少最终——除了 query* 方法和 getElementById()。不确定 Safari 是否支持其中的大部分(大约 2015-10)。而且我认为还没有人支持 find()/findAll().