【发布时间】:2023-02-06 21:24:40
【问题描述】:
只需要保留li 标签。
在其他标签中,只保留文本。
我的代码:
let html = `
<ol>
<li><a href="#"><code>foo</code> link text</a>;</li>
<li><a href="#"><code>bar</code> link text</a>;</li>
</ol>
<p>Paragraph text <code>baz</code> and <code>biz</code> text.</p>
<p>Paragraph text.</p>
`;
html = `<body>${html}</body>`;
let parsed = new DOMParser().parseFromString( html, 'text/html' );
function testFn( node ) {
node.childNodes.forEach( function( e ) {
testFn( e );
if ( e.nodeType !== Node.ELEMENT_NODE ) return;
if ( e.nodeName.toLowerCase() !== 'li' ) {
e.replaceWith( ...e.childNodes );
}
});
}
testFn( parsed.body );
console.log( parsed.body.innerHTML );
结果:
<li>foo link text;</li>
<li>bar link text;</li>
<p>Paragraph text <code>baz</code> and <code>biz</code> text.</p>
<p>Paragraph text.</p>
我需要这样的结果:
<li>foo link text;</li>
<li>bar link text;</li>
Paragraph text baz and biz text.
Paragraph text.
为什么函数不处理段落?
【问题讨论】:
-
如果您进行调试,您会注意到它永远不会到达您的
<p>元素。它循环通过<ol>然后退出。
标签: javascript html recursion