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.
i.e.
1 | <a href="http://www.vikaskbh.com">Vikas Bhagwagar</a> |
jQuery
1 2 3 | 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.
1 2 3 4 | <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.
1 | var valid_links_regex = "example|assignment"; |
Matching with Text nodes
1 2 3 4 | var re = new RegExp(valid_links_regex, 'ig'); if(TEXT.match(re)) { // your code here } |
Using regular expression with jQuery anchor selector
1 2 3 4 5 6 | $('a').each(function(k,v){ 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
1 2 3 4 5 6 7 8 9 10 11 | 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; } |
So, what do you think ?