简体   繁体   English

将HTML字符串解析为DOM并将其转换回字符串

[英]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 ,因为我想更改某些特定elementsinnerHTML 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 parseDOM并使用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: 我尝试的是将innerHTMLouterHTML (均尝试)分配给这样的变量:

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. 我发现有很多innerHTMLouterHTML示例,但就我而言,出了点问题。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM