Dan382
Dan382

Reputation: 986

Hiding a div that contains a specific string in jQuery

Tried the folling based on another question:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-latest.min.js"></script>
<script type="text/javascript">
$("div p:contains('text')").parent('div').hide();
</script>

<title>test</title>
</head>

<body>

<div>
<p>text</p>
</div>

</body>
</html>

But it doesn't work. AM I missing something obvious?

Upvotes: 5

Views: 19978

Answers (3)

Ashutosh Jindal
Ashutosh Jindal

Reputation: 18869

It looks like there is no problem with the code.

$(document).ready(function () {
    $("div p:contains('text')").parent('div').hide();
});

Check this out.

Update

All check this out. This is a case-insensitive version of the above:

// Add the case-insensitive selector
$.expr[":"].containsNoCase = function(el, i, m) {
    var search = m[3];
    if (!search) return false;

    var pattern = new RegExp(search,"i");
    return pattern.test($(el).text());
};

$(document).ready(function() {
    $("div p:containsNoCase('text')").parent('div').hide();
});

Upvotes: 4

czinkos
czinkos

Reputation: 111

You missed the document.ready event. See http://api.jquery.com/ready/

<script type="text/javascript">
$(document).ready(function () {
   $("div p:contains('text')").parent('div').hide();
});
</script>

Upvotes: 9

valscion
valscion

Reputation: 590

You need to run your jQuery stuff only after the DOM is finished loading.

$(document).ready(function() {
  $("div p:contains('text').parent('div').hide();
});

Upvotes: 6

Related Questions