Search code examples
jquerytextfind

How can I find elements by text content with jQuery?


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 IDs. (Then I then need to find that element's parent.)


Solution

  • 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>