Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top