问题
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);
});
回答1:
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);
回答2:
Try:
var elements = [];
$('body *').each(function(){
if($(this).html()=="{{ <sometext> }}"){
elements.push($(this).html());
}
});
demo
回答3:
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
}
});
回答4:
You can use the jQuery map function to test each element against a regular expression and return an array of elements:
var elements = $("*").map(function () {
if (/{{.*}}/g.test($(this).text())) {
return this;
}
}).get();
来源:https://stackoverflow.com/questions/21172170/how-get-an-element-if-its-inner-text-matches-a-pattern-in-jquery