以字符串形式返回模板标签的内容

Joh*_*n64 1 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);   
    }
}
Run Code Online (Sandbox Code Playgroud)

sid*_*ker 5

如果只需要HTML作为字符串,则可以使用通常的方法.innerHTML;像这样:

document.querySelector("template").innerHTML
Run Code Online (Sandbox Code Playgroud)

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

document.querySelector("template").content.textContent
Run Code Online (Sandbox Code Playgroud)

如果您想实际遍历template子节点或对其内容进行任何其他操作,则需要使用该.content属性,该属性返回DocumentFragment

从你有childrenfirstElementChildlastElementChildchildElementCount,和find()findAll()querySelector()querySelectorAll()getElementById,至少最终会(除了和query*方法之外)getElementById(),我不确定IE / Edge和Safari是否支持大多数方法(大约2015年10月)。我认为还没有人支持find()/ findAll()