gpt4 book ai didi

Jquery - 仅删除 div 中的文本内容

转载 作者:行者123 更新时间:2023-12-03 21:28:22 24 4
gpt4 key购买 nike

是否可以仅删除 div 中的文本内容,即保持所有其他元素不变,仅删除直接位于 div 内的文本?

最佳答案

这应该可以解决问题:

$('#YourDivId').contents().filter(function(){
return this.nodeType === 3;
}).remove();

或者使用 ES6 箭头函数:

$('#YourDivId').contents().filter((_, el) => el.nodeType === 3).remove();

如果你想让你的代码更具可读性并且只需要支持IE9+,你可以使用node type constants 。就我个人而言,我还将过滤器函数拆分出来并命名它,以便重用和更好的可读性:

let isTextNode = (_, el) => el.nodeType === Node.TEXT_NODE;

$('#YourDivId').contents().filter(isTextNode).remove();

这是包含所有示例的片段:

$('#container1').contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
}).remove();

$('#container2').contents().filter((_, el) => el.nodeType === Node.TEXT_NODE).remove();

let isTextNode = (_, el) => el.nodeType === Node.TEXT_NODE;

$('#container3').contents().filter(isTextNode).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container1">
<h1>This shouldn't be removed.</h1>
This text should be removed.
<p>This shouldn't be removed either.</p>
This text should also be removed.
</div>

<div id="container2">
<h1>This shouldn't be removed.</h1>
This text should be removed.
<p>This shouldn't be removed either.</p>
This text should also be removed.
</div>

<div id="container3">
<h1>This shouldn't be removed.</h1>
This text should be removed.
<p>This shouldn't be removed either.</p>
This text should also be removed.
</div>

关于Jquery - 仅删除 div 中的文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3421999/

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