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

jquery_logo

 

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

i.e.

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

jQuery

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?

i.e.

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

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

$('a').each(function(k,v){
    var re = new RegExp(valid_links_regex, 'ig');
	if($(this).text().match(re)) {
		// do something
	}
});

Final Code

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)) {
            links.push($(this));
        }
    });
    return links;
}

 

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

 
Previous Post

GeForce GTX graphics card DVI-VGA display converter doesn’t work – FIX

Next Post

Flat UI – Simple HTML tabs without jQuery or any other library

Related Posts