3

If you have HTML like:

<div class="text">Good Stuff Hide Me</div>
<div class="text">Great Stuff Hide Me</div>
<div class="text">Best Stuff Hide Me</div>

and want to hide just "Hide Me" in every instance of div.text so you're left with

Good Stuff
Great Stuff
Best Stuff

How would you do that with jQuery?

This $("div:contains('Hide Me')").hide(); hides the entire string. How can you isolate the text you want to hide?

Erik Berger
  • 599
  • 1
  • 10
  • 24
  • Hide Me would need to be enclosed in an element. The best jQuery could do the recreate the whole `.text` block and create a new element. You would be better off starting with `Hide Me`. – Daniel Imms Jan 31 '14 at 20:53
  • Remove the text or hide the text? There is a big difference and one I don't know if it can be cleanly done.... – useSticks Jan 31 '14 at 20:53
  • @useSticks hide is fine. I'll edit the question. – Erik Berger Jan 31 '14 at 20:54

3 Answers3

9

If you want to actually remove the text, use:

$('div.text').text(function (i, t) {
    return t.replace(' Hide Me', '');
})

jsFiddle example

To hide it, use:

$('div.text').html(function (i, t) {
    return t.replace('Hide Me', '<span class="hidden">Hide Me</span>');
})

with the CSS .hidden { display:none; }

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Perfect. The only thing I want to add is that my example had a class name so it would be $('div.text') . In my actual code I have the "Text to be hidden" text in other divs that I don't want to hide so just needed to specify the ones I wanted. Little nitpick for a great answer. – Erik Berger Jan 31 '14 at 21:11
1

Another option, other than useSticks's, is to do what j08691 suggested but to then to use $('.hidden').contents().unwrap() (or the native alternative) as shown in this answer. This way, you could dynamically tell it what you want to hide/unhide, perhaps based on what the user enters.

Community
  • 1
  • 1
Charlie G
  • 814
  • 9
  • 22
-1

j08691 has it, but if you are going to be switching it to a span to hide it, it implies that you want to bring it back. You would be wise to think of splitting the text into 2 tags yourself so that you can more cleanly search for it and handle bringing it back easier later.

 <div class="text">Good Stuff <span class="hideMe">Hide Me</span></div>
 <div class="text">Great Stuff <span class="hideMe">Hide Me</span></div>
 <div class="text">Best Stuff <span class="hideMe">Hide Me</span></div>

So you have

 $(".hideMe").hide()
 $(".hideMe").show()
useSticks
  • 883
  • 7
  • 15