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.)
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.
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.
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.
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).
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>
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With