Reputation: 609
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
Reputation: 207861
If you want to actually remove the text, use:
$('div.text').text(function (i, t) {
return t.replace(' Hide Me', '');
})
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;
}
Upvotes: 9
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
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