Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check whether a string contains a substring in jQuery?
The jQuery :contains() Selector is used to check whether a string contains a substring in jQuery. This selector selects elements that contain the specified text as a substring, making it useful for filtering and styling elements based on their content.
Set the substring you are searching for in the contains() method as shown below −
$(document).ready(function(){
$("p:contains(Video)").css("background-color", "blue");
});
In the above example, all paragraph elements containing the word "Video" will have their background color changed to blue.
Example
Now, let us see the complete code to check whether a string contains a substring or not −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p:contains(Video)").css("background-color", "blue");
});
</script>
</head>
<body>
<h1>Tutorialspoint</h1>
<p>This is demo text.</p>
<p>Free Tutorials</p>
<p>Free Video Tutorials</p>
</body>
</html>
In this example, only the paragraph containing "Free Video Tutorials" will have a blue background because it contains the substring "Video". The other paragraphs will remain unchanged.
The :contains() selector is case-sensitive and performs an exact substring match, making it a simple yet effective way to filter elements based on their text content in jQuery.
