prevailrob
prevailrob

Reputation: 275

Using Jquery to hide <p> based on its contents

Im trying to achieve the following:

A certain page will have a series of strings, which are replaced with database content if it exists.
For example:

<h2 class="label">Title:</h2>
<p class="value">{{Title}}</p>

Would become:

<h2 class="label">Title:</h2>
<p class="value">This is the title</p>

The problem is, if the database row for {{Title}} has never been entered, it displays the {{Title}} instead of replacing it with whitespace. So what id like to do is, with jquery, if .value contains {{, hide the whole element, in the same way display:none would.

Is this possible?

Thanks in advance.
Rob

Upvotes: 4

Views: 3116

Answers (4)

Kobi
Kobi

Reputation: 138117

$("p.value:contains('{{')").hide();

Edit:
There's a claim this code is slower. It should be said this is fairly basic, and in fact runs about 3 times faster.
Check this example (first one is slower): http://jsbin.com/ikite

Upvotes: 5

cllpse
cllpse

Reputation: 21727

$(function () // when DOM is ready for manipulation, do:
{
    // for each of the p-elements in the DOM (add your own context or class-scope
    // or whatever you can do to narrow down the list of elements here):
    $("p").each(function () 
    {
        // cache the element (always a good idea when doing multiple operations
        // on the same entity):
        var that = $(this);

        // if the text of the element is "{{Title}}" then hide the element:
        if (that.text() == "{{Title}}") that.hide();

        // alternatively you can do:

        // if the the characters "{{" exists at any position in the text of the
        // element, hide it:
        if (that.text().indexOf("{{") > -1) that.hide();
    });
});

Upvotes: 6

MSK
MSK

Reputation: 84

Try:

$('p.value').each(function(i,e){
  if ($(e).text().match(/^{{.*}}$/)) {
    $(e).hide();
  }
});

Upvotes: 3

smack0007
smack0007

Reputation: 11356

Could you not just give the p a class of title?

<h2 class="title label">Title:</h2>
<p class="title value"></p>

And then to hide / show it:

if(title != '')
{
    $('p.title.value').text(title);
}
else
{
    $('.title').hide();
}

Upvotes: 0

Related Questions