:::: MENU ::::

jQuery :contains() selector regex for matching text within elements



jQuery contains() selector simply matches text within selectors.  It’s also case sensitive, so we’ve very limitation for selecting or finding elements match approximately.


<a href="http://www.vikaskbh.com">Vikas Bhagwagar</a>


if($('a:contains("Vikas")').length) {
console.log("my link exists");

How about links those are inserted dynamically into DOM and we want to make sure if they exist before manipulation of some action?


<a href="http://www.example1.com">Example 1</a>
<a href="http://www.assignment1.com">Assignment 1</a>
<a href="http://www.example2.com">Example 2</a>
<a href="http://www.assignment2.com">Assignment 2</a>

What If we want to find, links containing text “Example” or “Assignment” exist?
If yes, how many?

Here jQuery contains() selector won’t work because it needs explicit arguments like $(‘a:contains(“Example 1”)’)

So, here regular expression can do the job.

Regular expression for matching link text.

var valid_links_regex = "example|assignment";

 Matching with Text nodes

var re = new RegExp(valid_links_regex, 'ig');
if(TEXT.match(re)) {
  // your code here

 Using regular expression with jQuery anchor selector

    var re = new RegExp(valid_links_regex, 'ig');
	if($(this).text().match(re)) {
		// do something

Final Code

Find number of links that matches regular expression

var findMyLinks = function () {
    var valid_links_regex = "example|assignment";
    var links = []
    $('a').each(function (k, v) {
        var re = new RegExp(valid_links_regex, 'ig');
        if ($(this).text().match(re)) {
    return links;


So, what do you think ?