[英]Parse HTML String to DOM and convert it back to string
I've got an HTML
string
eg '<p><span class="text">Hello World!</span></p>'
我有一个
HTML
string
例如'<p><span class="text">Hello World!</span></p>'
I parse this HTML
string
to DOM
using DOMParser().parseFromString()
, because I want to change the innerHTML
of some specific elements
. 我使用
DOMParser().parseFromString()
HTML
string
解析为DOM
,因为我想更改某些特定elements
的innerHTML
。 That's why I parse
the HTML
string
to DOM
and with getElementByClassName
I get all my elements and loop through them to change it innerHTML
. 这就是为什么我将
HTML
string
parse
为DOM
并使用getElementByClassName
获取所有元素并遍历它们以将其更改为innerHTML
。 This works so far. 到目前为止,该方法有效。
After I changed the innerHTML
, I try to convert the new DOM
back to a string
. 更改
innerHTML
,我尝试将新的DOM
转换回string
。 I can't figure out how. 我不知道怎么办。 What I tried is to assign the
innerHTML
or outerHTML
(tried both) to a variable like this: 我尝试的是将
innerHTML
或outerHTML
(均尝试)分配给这样的变量:
const parser = new DOMParser();
const doc = parser.parseFromString("<p>Hello World!</p>", "text/html");
console.log(doc.innerHTML) // undefined
console.log(doc.outerHTML) // undefined
const parser = new DOMParser(); const doc = parser.parseFromString("<p>Hello World!</p>", "text/html"); console.log(doc.innerHTML) // undefined console.log(doc.outerHTML) // undefined
I always get undefined
. 我总是
undefined
。 How can I parse it back to a string
? 如何将其解析回
string
? I found a lot examples with innerHTML
or outerHTML
, but in my case something went wrong. 我发现有很多
innerHTML
或outerHTML
示例,但就我而言,出了点问题。 Any ideas? 有任何想法吗?
DOMParser will always give you a document in return. DOMParser总是会给您一个文档作为回报。 Documents don't have an
innerHTML
property, but the document.documentElement
does, just like in a page's normal document
object: 文档没有
innerHTML
属性,但是document.documentElement
却有,就像页面的普通document
对象中一样:
const myHtmlString = '<p><span class="text">Hello World!</span></p>' const htmlDom = new DOMParser().parseFromString(myHtmlString, 'text/html'); console.log(htmlDom.documentElement.innerHTML);
Do note that a <head>
and <body>
will be created for you, if you don't pass those tags in yourself. 请注意,如果您自己不传递这些标记,则会为您创建
<head>
和<body>
。 If you only want the body, then: 如果只想要身体,则:
const myHtmlString = '<p><span class="text">Hello World!</span></p>' const htmlDom = new DOMParser().parseFromString(myHtmlString, 'text/html'); console.log(htmlDom.body.innerHTML);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.