jQuery code to hide

tag with specific text

Suppose your webpage has many <p> (Paragraph) tags/elements, and you want to hide those paragraph elements which have specific text or word. For example, hide all p tag element which have "jquery" word in it. This can be done easily using jQuery. jQuery has ":contains" selector which can be used to select p tags with specific text.

The code $("p:contains('Javascript')") will select all the <p> tag element which have text "Javascript" in it. But remember, ":contains" selector is case sensitive.

$('#btnHide').click(function() {
     $("p:contains('Javascript')").hide();
});
$('#btnReset').click(function() {
    $("p:contains('JavaScript')").show();
});

See result below


You might be aware that jQuery ":contains()" is case sensitive. So for ":contains", the word "Javascript" and "JavaScript" are different. If you have paid attention to above jQuery code, I have used different words in ":contains", yet it is working. In spite of ":contains" being case sensitive, the above jQuery code is working. Wondering?

Well, there is a way by which you can extend the default behavior of contains and make it case-insensitive.

Code to make jQuery :contains Case-Insensitive

jQuery.expr[':'].contains = function(a, i, m) {
 return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
See Complete Code

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...