jQuery: find element by text
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.)
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;
}
Fellas, I know this is old but hey I've this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:
var text = "text";
var search = $( "ul li label" ).filter( function ()
{
return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()
Hope someone in the near future finds it helpful.