Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

Jquery - Remove only text content from a 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should do the trick:

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

Or using an ES6 arrow function:

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...