Erik Berger
Erik Berger

Reputation: 609

jQuery Hide part of a string based on text

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?

Upvotes: 3

Views: 9126

Answers (3)

j08691
j08691

Reputation: 207861

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

Upvotes: 9

Charlie G
Charlie G

Reputation: 824

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.

Upvotes: 1

useSticks
useSticks

Reputation: 904

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()

Upvotes: -1

Related Questions