jQuery: select elements with a specific text
By Anatoly Mironov
There are situations when you want to select only dom elements which only have a specific content. jQuery provides a beautiful selector :contains:
$("a:contains(Pages)")
```But what if it isn't enough to just get all the elements which contain some word? Let's check what we get if we traverse all anchors on http://sv.wikipedia.org containing "wiki":
$(“a:contains(wiki)”).each(function(i) { console.log($(this).text()); });
[![](https://sharepointkunskap.files.wordpress.com/2012/02/jquery-contains-wiki.png "jquery-contains-wiki")](https://sharepointkunskap.files.wordpress.com/2012/02/jquery-contains-wiki.png) There is another, a generic way, to filter out elements, and it is called "filter". So a little regex check will do the trick.
$(“a”).filter(function() { return /look_for/i.test($(this).text()); }
(function ($, undefined) { if ($ === undefined) { throw “Dependency: jQuery is not defined. Please check javascript imports.”; } $.extend($.expr[’:’], { // :textEquals(text) textEquals: function(current, index, metadata, elements) { var regex = new RegExp("^" + metadata[3] + “$”); regex.ignoreCase = true; var text = current.textContent || current.innerText || jQuery(current).text() || “”; return regex.test(text); } }); } (jQuery));