Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery to hide <p> based on its contents

Tags:

jquery

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

like image 684
prevailrob Avatar asked Dec 10 '22 19:12

prevailrob


2 Answers

$(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();
    });
});
like image 111
cllpse Avatar answered Jan 04 '23 22:01

cllpse


$("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

like image 44
Kobi Avatar answered Jan 04 '23 23:01

Kobi