是否可以仅从div中删除文本内容,即保持所有其他元素不变,仅删除直接位于div中的文本?
发布于 2010-08-06 16:19:12
这应该能起到作用:
$('#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>
发布于 2014-12-29 05:52:51
假设HTML结构如下:
<div class="element-to-clean">
Content to be filtered out.
<span class="element-to-leave-intact">
Content to be left inthe element.
</span>
</div>您可以使用以下JavaScript + jQuery 2.1代码来实现您想要的行为:
$('.element-to-clean').html($('.element-to-clean').children());发布于 2010-08-06 16:19:25
你可以用简单的dom来实现:
var div=$("div")[0];
if(div.childNodes.length)
for(var i=0;i<div.childNodes.length;i++)
{
if(div.childNodes[i].nodeType===3)
div.removeChild(div.childNodes[i]);
}https://stackoverflow.com/questions/3421999
复制相似问题