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

时间:2015-09-28 22:24:45

标签: javascript jquery dom web-component html5-template

我想知道是否有办法在模板标签中获取元素的内容并将其作为字符串返回?目前它似乎正在返回[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);   
    }
}

1 个答案:

答案 0 :(得分:4)

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().