从 DOMParser 中获取所有 HTML 内容,不包括外部 body 标签

Get all HTML content from DOMParser, excluding the outer body tag

我在以下代码中使用 DOMParser

let doc = new DOMParser().parseFromString('<b>sample text</b> <i>sample text</i>', 'text/html');
document.querySelector('.js').append(doc.body);
<span><b>sample text</b> <i>sample text</i></span>
<span><b>sample text</b> <i>sample text</i></span>
<span class='js'></span>

当我 运行 它时,它正确地给出了 HTML 内容,但问题是 outer body 标签 也是包含在结果中,这使得内容有block显示。实际上,我需要保留 inline 显示,如前两个 span 所示。

我以为是因为 doc.body 语句,所以我尝试将其更改为 doc.body.firstChild (其中 returns 只有 b 元素)和 doc.body.children (returns [Object HTMLCollection]),但其中 none 有效。

如何解决?


注意: <span><b>sample text</b> <i>sample text</i></span>是我网页上的动态内容。

希望我的理解是正确的!您正在尝试显示与之前的 span 标签类似的内容。将字符串值分配给 innerHTML 内容可能会有所帮助,在这种情况下无需使用 DOMParser。可能使用 innerHTML 方式来保留内联样式。

const htmlContent = '<b>sample text</b>'
document.querySelector('.js').innerHTML = htmlContent;

如果仍然需要使用 DOMParser,那么您可能会这样做

document.querySelector('.js').innerHTML = doc.body.innerHTML

希望对您有所帮助!

尝试

document.querySelector('.js').append(...doc.body.children);

let doc = new DOMParser().parseFromString('<b>sample text</b> <i>sample text</i>', 'text/html');
document.querySelector('.js').append(...doc.body.children);
<span><b>sample text</b> <i>sample text</i></span>
<span><b>sample text</b> <i>sample text</i></span>
<span class='js'></span>