jquery find by innertext

jQuery Find by InnerText

As a web developer, I have often come across the need to find elements by their inner text using jQuery. It can be helpful in situations where we need to manipulate or extract data from the HTML document based on the text content of an element.

To find elements by their inner text in jQuery, we can use the :contains() selector. This selector is case-sensitive, and it matches any element that contains the specified text. We can use it with any valid CSS selector to narrow down our search to specific elements.

Example 1:

Let's say we have a div with a class name of "content" that contains multiple paragraphs. We want to find all the paragraphs that contain the word "Lorem" in them. Here's how we can do it:


$('.content p:contains("Lorem")');

This code will select all the paragraphs within the div with a class of "content" that contain the text "Lorem" in them.

Example 2:

We can also use the :contains() selector with the parent() method to get the parent element that contains the specified text. Let's say we have a list of items, and we want to select the list item that contains the text "Apple" in it.


$('li:contains("Apple")').parent();

This code will select the list item that contains the text "Apple" and then return its parent element.

Example 3:

Another way to find elements by their inner text is by using the filter() method. This method takes a function as an argument, and we can use it to filter out elements based on their inner text. Let's say we have a table with multiple rows, and we want to select the row that contains the text "John" in it.


$('table tr').filter(function() {
  return $(this).text().indexOf('John') !== -1;
});

This code will select the row that contains the text "John" in it and return it.

These are a few ways we can find elements by their inner text using jQuery. The :contains() selector is the easiest and most straightforward way to accomplish this task.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe