Hiding a div that contains a specific string in jQuery
Asked Answered
K

3

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?

Kennie answered 2/8, 2012 at 12:19 Comment(0)
A
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>
Attractant answered 2/8, 2012 at 12:26 Comment(1)
Thanks! Cant believe I missed that. What would the code look like to target a 'Buy Now' input button instead of a div?Kennie
P
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();
});
Pole answered 2/8, 2012 at 12:26 Comment(0)
D
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();
});
Davies answered 2/8, 2012 at 12:27 Comment(4)
Downvoted because of eval. You could use new RegExp to create a regular expression without eval.Pole
@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 ?Davies
Ah got it : #647097Davies
How can you hide only the div containing the text? Currently its hiding all of the parent content.Retrogression

© 2022 - 2024 — McMap. All rights reserved.