5

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?

Dan382
  • 976
  • 6
  • 22
  • 44

3 Answers3

9

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>
czinkos
  • 111
  • 3
  • Thanks! Cant believe I missed that. What would the code look like to target a 'Buy Now' input button instead of a div? – Dan382 Aug 02 '12 at 13:51
6

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

$(document).ready(function() {
  $("div p:contains('text').parent('div').hide();
});
valscion
  • 580
  • 4
  • 13
4

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();
});
Ashutosh Jindal
  • 18,501
  • 4
  • 62
  • 91
  • Downvoted because of eval. You could use `new RegExp` to create a regular expression without eval. – valscion Aug 02 '12 at 12:55
  • @VesQ, I have updated my answer to replace eval with RegExp. Also, I searched around a bit but could not find out why eval is evil ? Could you shed some light on it ? – Ashutosh Jindal Aug 02 '12 at 13:24
  • Ah got it : http://stackoverflow.com/questions/646597/eval-is-evil-so-what-should-i-use-instead – Ashutosh Jindal Aug 02 '12 at 13:27
  • How can you hide only the div containing the text? Currently its hiding all of the parent content. – Shae Oct 25 '20 at 15:52