Check if the element contains specific text in jQuery

Description

The following code shows how to check if the element contains specific text.

Example


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--  w w  w.j a  v  a 2 s  .  c o  m-->
$("div").one('click', function () {
if ($(this).is(":first-child")) {
$("p").text(":first-child");
} else if ($(this).is(".blue,.red")) {
$("p").text("It's a blue or red div.");
} else if ($(this).is(":contains('java2s.com')")) {
$("p").text("It's java2s.com!");
} else {
$("p").html("It's nothing <em>special</em>.");
}
});
});
</script>
<style>
div.middle { color: red; }
</style>
</head>
<body>
<body>
<div>java2s.com</div>
<div class="blue">jav a2s.com</div>
<div class="red">java2s.com</div>
<div><span>java2s.com</span>java 2s.com</div>
<div class="blue">java2s.co m</div>
<p>java2s.com</p>
</body>
</html>

Click to view the demo

The code above generates the following result.

Check if the element contains specific text in jQuery
Home »
  Javascript Tutorial »
    jQuery »
      jQuery DOM
...
Add a selected element to a tag and set it...
Add an element returned from document.getEl...
Add before and after to make the selected e...
Add hard coded tag before an element in jQu...
Add new element and set CSS property in jQu...
Add new html tag to body and set its class ...
Add text node create by document.createText...
Add text node with prepend in jQuery
Add text to empty table cell and apply styl...
Append Text node created by document.create...
Append cloned paragraph to document body in...
Append hard code HTML tags to a paragraph i...
Append hard code tag to body tag in jQuery
Append selected element to all paragraphs i...
Change element id by using its own text val...
Change inner html and set its color in jQue...
Change text to uppercase in jQuery
Change the tag with replaceWith and keep th...
Check if the element contains specific text...
Check if the element is the first child in ...
Check to see if the parent element is a for...
Clear an attribute in jQuery
Combines the text of all the elements in a ...
Convert elements to array with .toArray() i...
Create a paragraph clone then add a hard co...
Get HTML content in jQuery
Get image src attribute value in jQuery
Get text and attribute in jQuery
Get text from first paragraph and set it as...
Get the content of a paragraph and convert ...
Get the title attribute from an image eleme...
Insert a cloned element after selected elem...
Insert a hardcoded element after in jQuery
Insert a selected element after in jQuery
Insert a selected element with prepend in j...
Insert hard coded HTML element after select...
Insert hardcoded HTML after all paragraphs ...
Insert hardcoded element to a span element ...
...