The ':contains(text) Selector' is used to select the elements, which matches the text specified.
Say for example, we have 5 <p> elements in our HTML document.
<p class = "para1"> First Paragraph </p> <p class = "para2"> Second Paragraph </p> <p class = "para3"> Third Paragraph </p> <p class = "para4"> Fourth Line </p> <p class = "para5"> Fifth Part </p>
And we want to search, which all <p> elements has the word Paragraph.
Let us see with the below example.
<html>
<head>
<title> My First Programme </title>
</head>
<body>
<h1> JQuery </h1>
<div class = "newClass">
<p class = "para1"> First Paragraph </p>
<p class = "para2"> Second Paragraph </p>
<p class = "para3"> Third Paragraph </p>
<p class = "para4"> Fourth Line </p>
<p class = "para5"> Fifth Part </p>
</div>
<button> Click me </button>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"> </script>
<script>
$('button').click( function() {
$('p:contains("Paragraph")').text("The word with paragraph got replaced")
});
</script>
</body>
</html>
So, if you see the above code. We can see that there are five <p> elements.
<div class = "newClass"> <p class = "para1"> First Paragraph </p> <p class = "para2"> Second Paragraph </p> <p class = "para3"> Third Paragraph </p> <p class = "para4"> Fourth Line </p> <p class = "para5"> Fifth Part </p> </div>
And on button click, the contents of first, second and third <p> element gets replaced with 'The word with paragraph got replaced' because they contain the word 'Paragraph'.
And this happened with the 'p:contains("Paragraph")' element selector.
$('button').click( function() {
$('p:contains("Paragraph")').text("The word with paragraph got replaced")
});The moment the button is clicked, JQuery statement gets triggered.
$('p:contains("Paragraph")').text("The word with paragraph got replaced")And it searches for the <p> elements that has the word 'Paragraph'.
And it finds the first, second and third <p> elements has the word 'Paragraph'.
<p class = "para1"> First Paragraph </p> <p class = "para2"> Second Paragraph </p> <p class = "para3"> Third Paragraph </p>
So, the contents of the above <p> elements hets replaced.