SamotnyPocitac
SamotnyPocitac

Reputation: 402

jQuery find text and hide that text

I'm trying to hide the text from the paragraphs. The problem is that the script find the text and remove the whole paragraph. I want to remove only that text that is searched for. Demo

<div class='article'>    
    <p>Text may refer to: Contents. 1 Computers and electronics; 2 Arts and entertainment; 3 See also. Text (journal), an academic journal of language, discourse, and...</p>
</div>

$(function() {
    var foundin = $('.article p:contains("journal")');
    $(foundin).hide();
});

Upvotes: 0

Views: 112

Answers (4)

Skriptotajs
Skriptotajs

Reputation: 874

  • It's better to use html() than text(), because there might me some HTML code in paragraph.
  • You must use regexp to replace all the occurrences in text.
  • You should use each, because some other answers won't work if there will be multiple paragraphs with matches

http://jsfiddle.net/aanN2/7/

$(function() {
    $('.article p:contains("journal")').each(function(){
        $(this).html($(this).html().replace(/journal/g, ""))
    });
});

Upvotes: 1

tarmaq
tarmaq

Reputation: 422

var foundin = $('.article p:contains("journal")');
foundin.text(foundin.text().replace(/journal/g, ""))

http://jsfiddle.net/aanN2/5/

Upvotes: 4

adeneo
adeneo

Reputation: 318182

Wrap the text in hidden spans with a class

$(function() {
    var text = 'journal';
    $('.article p').html(function(_,html) {
        return html.replace(new RegExp('('+text+')','g'), '<span class="hidden" style="display:none">$1</span>')
    });
});

to show it again you can do

$('.hidden').show();

FIDDLE

Upvotes: 1

Oscar Paz
Oscar Paz

Reputation: 18292

$(function() {
    var foundin = $('.article p:contains("journal")');
    var html = foundin.html();
    html = html.replace('journal', '<span class="hidden">journal</span>');
    $(foundin).html(html);
});

And the CSS

.hidden
{
    display: none;
}

This way, by changing the .hidden style you can highlight the text instead hiding it. This solution won't affect the markup of the rest of the paragraph.

jsfiddle.

Upvotes: 1

Related Questions