Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding a div that contains a specific string in jQuery

Tags:

jquery

hidden

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?

like image 926
Dan382 Avatar asked Aug 02 '12 12:08

Dan382


People also ask

How do I hide content inside a div?

You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.

How do I hide a specific div?

We hide the divs by adding a CSS class called hidden to the outer div called . text_container . This will trigger CSS to hide the inner div.

How do we hide content in jQuery?

jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page).

Which method is used to hide selected element jQuery?

The hide() is an inbuilt method in jQuery used to hide the selected element. Syntax: $(selector). hide(duration, easing, call_function);


3 Answers

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>
like image 163
czinkos Avatar answered Oct 13 '22 13:10

czinkos


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

$(document).ready(function() {
  $("div p:contains('text').parent('div').hide();
});
like image 34
valscion Avatar answered Oct 13 '22 15:10

valscion


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();
});
like image 4
Ashutosh Jindal Avatar answered Oct 13 '22 14:10

Ashutosh Jindal