Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get an element if its inner text matches a pattern in jquery?

Consider a html like below,

<div id="test">
{{ sometext }}
</div>
<span class="testing">
{{ asdknfsdf }}
</span>

I want to get all the elements whose inner text matches {{ <sometext> }} in jquery. I tried the below code, but I could not get the elements properly. What am I missing here?

var elements = [];
$('*:contains("{{ .* }}")').each(function(){
   elements.push(this); 
});
like image 236
NEO Avatar asked Jan 16 '14 20:01

NEO


3 Answers

Several things:

1) "Could not get the elements properly" isn't terribly descriptive. Are you getting no results? Unexpected results?

2) By using a selector of *:contains, you are asking for every element that contains the specified text. That means you'll html, body, and other parent elements as well as the nearest div. Scope your selector to just div elements, or even better, to a class that you know might contain the expected result.

3) You can simplify your logic by simply calling makeArray() on the result of your selector:

var elements = $.makeArray($('body *:contains("{{ sometext }}")'));
console.log('elements ::', elements);
like image 183
Palpatim Avatar answered Nov 15 '22 04:11

Palpatim


I looked at the :contains() selector in JQuery, and I don't think that it does regular expressions - you will have to make a regular expression and then loop through your elements to look for a match. This is theoretical, but should get you started:

var reg = new RegExp("\{\{(.*)\}\}","g");
$('body *').each(function(i) {
   if(reg.test($(this)/text())) {
     //do something
   }
});
like image 43
Eric J. Avatar answered Nov 15 '22 04:11

Eric J.


Try:

 var elements = [];
$('body *').each(function(){
    if($(this).html()=="{{ <sometext> }}"){
    elements.push($(this).html());
    }
});

demo

like image 44
tilda Avatar answered Nov 15 '22 04:11

tilda