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);
});
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);
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
}
});
Try:
var elements = [];
$('body *').each(function(){
if($(this).html()=="{{ <sometext> }}"){
elements.push($(this).html());
}
});
demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With