![](/img/trans.png)
[英]How to remove whole HTML, HEAD tags and BODY tag from string with HTML using JavaScript?
[英]How to serialize HTML without head and body tags using jsdom
我想从 html 文档中清除一些标签,如下所示:
const { JSDOM } = require('jsdom');
function clearAnchorTags(pDom: JSDOM) {
if (typeof pDom === 'string') {
pDom = new JSDOM(pDom);
}
// Get all anchor tags from dom
for (const anchorTag of pDom.window.document.querySelectorAll('a')) {
for (const child of anchorTag.children) {
if (child.nodeName === 'EM') {
const node = pDom.window.document.createTextNode(child.textContent);
anchorTag.replaceChild(node, child);
}
if (child.nodeName === 'B') {
const node = pDom.window.document.createTextNode(child.textContent);
anchorTag.replaceChild(node, child);
}
if (child.nodeName === 'U') {
const node = pDom.window.document.createTextNode(child.textContent);
anchorTag.replaceChild(node, child);
}
}
}
// return as string just as we received it -- also replace with space
return pDom.serialize().replace(/ /g, ' ');
}
问题似乎是最后的 serialize() 方法,因为它返回一个功能齐全的 HTML 文档。
我需要它没有<html>, <head> and <body>
标签。 我只需要一个 HTML 片段。
我解决了我的问题
return pDom.window.document.body.innerHTML.replace(/ /g, ' ');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.