jQuery: find element by text

sisko picture sisko · Sep 6, 2011 · Viewed 337.2k times · Source

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.)

Answer

Rocket Hazmat picture Rocket Hazmat · Sep 6, 2011

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>