下面,就分别说明一下这3种转换方法
Range API
Range API
给我们提供了一个叫做
createContextualFragment
的方法。使用这个方法,我们就可以生成一个
DocumentFragment
,这个DocumentFragment里面包含了由Html字符串解析而成的DOM节点。
const range = document.createRange();
const fragment = range.createContextualFragment(htmlString);
Template
我们可以创建一个
template
标签元素,然后将这个Html字符串赋值给tempate的
innnerHTML
属性。这样,template的content属性,即
template.content
就会变为一个DocumentFragment,这个DocumentFragment里面就是由Html字符串解析而成的DOM节点。
const template = document.createElement('template');
template.innerHTML = htmlString;
const fragment = template.content;
DOMParser
使用
DOMParser.parseFromString()
方法,我们可以将一个Html或Xml字符串解析为一个
HTMLDocument
(or
XMLDocument
)对象,这个对象里面就包含了我们所需的DOM节点。
const parser = new DOMParser();
// HTMLDocument(<html><body>...parsed nodes</body></html>)
const doc = parser.parseFromString(htmlString, "text/html"); // 第2个参数为mimeType,可以为 text/html, text/xml 等等这些
// 解析好的DOM节点
const nodes = doc.body;
以上就是3种将Html字符串转换为DOM节点的方式,使用哪一个都可以。但个人还是喜欢使用第3种,因为它的语义更加明确,而且可以支持转换
text/html
,
text/xml
,
application/xml
,
application/xhtml+xml
,
image/svg+xml
这些类型,功能更加强大。
JavaScript Parse and Convert Raw HTML String to DOM Nodes
--更新于 2023-07-17 11:46:27
粤ICP备13044925号