Find text string using jQuery?

Keith Donegan picture Keith Donegan · May 29, 2009 · Viewed 355.1k times · Source

Say a web page has a string such as "I am a simple string" that I want to find. How would I go about this using JQuery?

Answer

Tony Miller picture Tony Miller · May 29, 2009

jQuery has the contains method. Here's a snippet for you:

<script type="text/javascript">
$(function() {
    var foundin = $('*:contains("I am a simple string")');
});
</script>

The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/

One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')