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

元气小坏坏 提交于 2021-02-08 15:19:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!