HTML dom 字符串创建元素,javascript - Creating a new DOM element from an HTML string using built-in DOM meth...

这篇博客介绍了HTML5中的template元素,它用于声明可复用的HTML片段,这些片段可以在脚本中使用。template元素的内容在DOM中表现为DocumentFragment,允许将HTML字符串转换为DOM元素。由于template元素对内容没有限制,因此避免了在div等元素中设置innerHTML时可能出现的问题。然而,template在某些旧浏览器中不被支持,如Internet Explorer。如果你的目标用户主要使用现代浏览器,可以立即使用template元素,否则可能需要等待更广泛的浏览器兼容性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTML 5 introduced the element which can be used for this purpose (as now described in the WhatWG spec and MDN docs).

A element is used to declare fragments of HTML that can be utilized in scripts. The element is represented in the DOM as a HTMLTemplateElement which has a .content property of DocumentFragment type, to provide access to the template's contents. This means that you can convert an HTML string to DOM elements by setting the innerHTML of a element, then reaching into the template's .content property.

Examples:

/**

* @param {String} HTML representing a single element

* @return {Element}

*/

function htmlToElement(html) {

var template = document.createElement('template');

html = html.trim(); // Never return a text node of whitespace as the result

template.innerHTML = html;

return template.content.firstChild;

}

var td = htmlToElement('

foo'),

div = htmlToElement('

nested stuff
');

/**

* @param {String} HTML representing any number of sibling elements

* @return {NodeList}

*/

function htmlToElements(html) {

var template = document.createElement('template');

template.innerHTML = html;

return template.content.childNodes;

}

var rows = htmlToElements('

foobar');

Note that similar approaches that use a different container element such as a div don't quite work. HTML has restrictions on what element types are allowed to exist inside which other element types; for instance, you can't put a td as a direct child of a div. This causes these elements to vanish if you try to set the innerHTML of a div to contain them. Since s have no such restrictions on their content, this shortcoming doesn't apply when using a template.

However, template is not supported in some old browsers. As of April 2021, Can I use... estimates 96% of users globally are using a browser that supports templates. In particular, no version of Internet Explorer supports them; Microsoft did not implement template support until the release of Edge.

If you're lucky enough to be writing code that's only targeted at users on modern browsers, go ahead and use them right now. Otherwise, you may have to wait a while for users to catch up.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值