以字符串形式返回模板标签的内容 [英] Returning contents of template tag as string

查看:268
本文介绍了以字符串形式返回模板标签的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以获取模板标记中元素的内容并将其作为字符串返回?目前看来,它正在沿[object document fragment]上的行返回某些内容,但只需要其中的html内容.

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

推荐答案

如果只需要将HTML作为字符串,则可以使用通常的.innerHTML来实现.像这样:

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

如果您想使用textContent,则可以从.content.textContent获取它;像这样:

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

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

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

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.

据此您具有childrenfirstElementChildlastElementChildchildElementCountfind()findAll()querySelector()querySelectorAll()getElementById;至少最终-除了query*方法和getElementById()之外,我不确定IE/Edge和Safari是否支持大多数功能(大约2015-10).而且我认为还没有人支持find()/findAll().

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

这篇关于以字符串形式返回模板标签的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆