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
Rocket's answer doesn't work.
<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>
I simply modified his DEMO here and you can see the root DOM is selected.
$('div:contains("test"):last').css('background-color', 'red');
add ":last" selector in the code to fix this.
Yes, use the jQuery contains selector.
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>
Best way in my opinion.
$.fn.findByContentText = function (text) {
return $(this).contents().filter(function () {
return $(this).text().trim() == text.trim();
});
};
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.
The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
<div>div1
<div>This is a test, nested in div1</div>
<div>Nested in div1<div>
</div>
<div>div2 test
<div>This is another test, nested in div2</div>
<div>Nested in div2</div>
</div>
<div>
div3
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>