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

Dav*_*vid 42 jquery

是否可以从div中删除文本内容,即保留所有其他元素完整,只删除直接在div中的文本?

Mar*_*ell 74

这应该做的伎俩:

$('#YourDivId').contents().filter(function(){
    return this.nodeType === 3;
}).remove();
Run Code Online (Sandbox Code Playgroud)

或使用ES6箭头功能:

$('#YourDivId').contents().filter((_, el) => el.nodeType === 3).remove();
Run Code Online (Sandbox Code Playgroud)

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

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

$('#YourDivId').contents().filter(isTextNode).remove();
Run Code Online (Sandbox Code Playgroud)

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

$('#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();
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 看起来答案很好,但是您能解释一下解决方法吗?什么是节点类型 === 3 ? (2认同)
  • @eirenaios https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType (2认同)

Art*_*ack 11

假设以下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>
Run Code Online (Sandbox Code Playgroud)

您可以使用以下JavaScript + jQuery 2.1代码实现所需的行为:

$('.element-to-clean').html($('.element-to-clean').children());
Run Code Online (Sandbox Code Playgroud)