Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: find element by text

Tags:

jquery

text

find

Can anyone tell me if it's possible to find an element based on its content rather than by an id or class?

I am attempting to find elements that don't have distinct classes or id's. (Then I then need to find that element's parent.)

like image 336
sisko Avatar asked Sep 06 '11 14:09

sisko


People also ask

How do I find a word in a string using jQuery?

How to find if a word or a substring is present in the given string. In this case, we will use the includes() method which determines whether a string contains the specified word or a substring. If the word or substring is present in the given string, the includes() method returns true; otherwise, it returns false.

How do I search for text in a div?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).


2 Answers

You can use the :contains selector to get elements based on their content.

Demo here

$('div:contains("test")').css('background-color', 'red');
<div>This is a test</div>  <div>Another Div</div>    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
like image 158
Rocket Hazmat Avatar answered Oct 06 '22 09:10

Rocket Hazmat


In jQuery documentation it says:

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination

Therefore it is not enough that you use :contains() selector, you also need to check if the text you search for is the direct content of the element you are targeting for, something like that:

function findElementByText(text) {     var jSpot = $("b:contains(" + text + ")")                 .filter(function() { return $(this).children().length === 0;})                 .parent();  // because you asked the parent of that element      return jSpot; } 
like image 20
yoav barnea Avatar answered Oct 06 '22 08:10

yoav barnea