gpt4 book ai didi

javascript - 从 HTML 节点获取不带文本的 html 结构

转载 作者:行者123 更新时间:2023-12-02 22:30:48 25 4
gpt4 key购买 nike

我想删除所有文本,只获取节点的 html 结构作为字符串。

这是我的节点,

<div class='myparent'>
<div>
<div class="pdp-product-price test" id="lll">
<span> 650 rupees</span>
<div class="origin-block">
<span> 1,500 rupees</span>
<span>-57%</span>
</div>
</div>
</div>
</div>

我想要的是这样的,

<div class='myparent'>
<div>
<div class="pdp-product-price test" id="lll">
<span></span>
<div class="origin-block">
<span></span>
<span></span>
</div>
</div>
</div>
</div>

我试过了,

$('.myparent').children().empty(); 

$('.myparent').children().text('');

但不幸的是他们删除了所有 child

最佳答案

您可以get all text nodes然后 .remove() 其中每个:

function nativeTreeWalker(parent) {
var walker = document.createTreeWalker(
parent,
NodeFilter.SHOW_TEXT,
null,
false
);

var node;
var textNodes = [];

while (node = walker.nextNode()) {
textNodes.push(node);
}
return textNodes;
}

const parent = document.querySelector('.myparent');
nativeTreeWalker(parent).forEach(node => node.remove());
console.log(parent.outerHTML);
<div class='myparent'>
<div>
<div class="pdp-product-price test" id="lll">
<span> 650 rupees</span>
<div class="origin-block">
<span> 1,500 rupees</span>
<span>-57%</span>
</div>
</div>
</div>
</div>

如果您不想弄乱现有的 HTML,请先克隆父级。

function nativeTreeWalker(parent) {
var walker = document.createTreeWalker(
parent,
NodeFilter.SHOW_TEXT,
null,
false
);

var node;
var textNodes = [];

while (node = walker.nextNode()) {
textNodes.push(node);
}
return textNodes;
}

const parent = document.querySelector('.myparent').cloneNode(true);
nativeTreeWalker(parent).forEach(node => node.remove());
console.log(parent.outerHTML);
<div class='myparent'>
<div>
<div class="pdp-product-price test" id="lll">
<span> 650 rupees</span>
<div class="origin-block">
<span> 1,500 rupees</span>
<span>-57%</span>
</div>
</div>
</div>
</div>

关于javascript - 从 HTML 节点获取不带文本的 html 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58908484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com