jQuery-仅从div中删除文本内容 [英] Jquery - Remove only text content from a div

查看:83
本文介绍了jQuery-仅从div中删除文本内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

is possible to remove only text content from a div, i.e. leave all other elements intact and only remove text that is directly inside a div?

推荐答案

这应该可以解决问题:

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

或使用ES6箭头功能:

Or using an ES6 arrow function:

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

如果您想使代码更具可读性,并且只需要支持IE9 +,则可以使用

If you want to make your code more readable and you only need to support IE9+, you can use the node type constants. Personally, I'd also split the filter function out and name it, for reuse and even better readability:

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

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

以下是所有示例的摘要:

Here's a snippet with all the examples:

$('#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中删除文本内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆