Skip to content
the poor coder

jquery find by innertext

Poor Man
Published
Reading time
2 min read
On this page

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:

JavaScript

$('.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.

JavaScript

$('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.

JavaScript

$('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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC