jQuery-仅从di删除文本内容

是否可以仅从div中删除文本内容,即保持所有其他元素完整并且仅删除直接位于div内部的文本?

David asked 2020-08-12T01:53:52Z
6个解决方案
74 votes

这应该可以解决问题:

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

或使用ES6箭头功能:

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

如果要使代码更具可读性,并且只需要支持IE9 +,则可以使用节点类型常量。 就个人而言,我还将过滤器功能分离出来并命名,以实现重用甚至更好的可读性:

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>

Mark Bell answered 2020-08-12T01:54:11Z
11 votes

假设以下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());
Artur Black answered 2020-08-12T01:54:35Z
3 votes

您可以使用简单的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]);
   }
mck89 answered 2020-08-12T01:54:56Z
2 votes

最简单的方法是这样的:

$('#div').html($('<div>').append($('*', '#div')).html());
reko_t answered 2020-08-12T01:55:18Z
2 votes

好吧,这可能不是最好的方法,但是我将div保存在一个变量中,然后在删除了标签中的所有内容之后,我使用了append:

$('.wpcf7 form p').each(function(i){
    var el = $(this).find('span');
    if(i==4)
    el = $(this).find('input');
    $(this).empty();
    $(this).append(el);
});
Mxlfa answered 2020-08-12T01:55:39Z
-6 votes
$('#yourDiv').text(''); 

这将删除您的文本内容

Gary Lindahl answered 2020-08-12T01:55:59Z
translate from https://stackoverflow.com:/questions/3421999/jquery-remove-only-text-content-from-a-div