How to select elements based on all their contents in jQuery?

I have a series <div/>as follows:

<div>.co.uk</div>  
<div>.com</div>  
<div>.gb.com</div>  
<div>.uk.com</div>  
<div>.net</div>

How to select only the divs, containing .co.uk, .com, .net.

If I use:

$('div:contains(".co.uk"), div:contains(".com"), div:contains(".net")`)

In doing so, you also select div .gb.comand .uk.com.

+3
source share
4 answers

You can use the method filterto check the content:

$('div').filter(function(){
  var t = $(this).text();
  return t == '.co.uk' || t == '.com' || t == '.net';
})

You may still want to filter out as many elements in the selector as possible to reduce the number of elements that the filter function should check. Even if the pseudo-class containscannot determine the exact match, it can still be used to reduce the result:

$('div:contains(".co.uk"), div:contains(".com"), div:contains(".net")`).filter(function(){
  var t = $(this).text();
  return t == '.co.uk' || t == '.com' || t == '.net';
})
+5

.each() , $(this).text():

$('div').each(function() {
    if ($(this).text().match(/^\.(com|net|co\.uk)$/)) {
        // ...
    }
});
+1

I would do this with a filter:

jQuery.fn.pickDomains = function() {
  var domains = jQuery.makeArray(arguments);
  return this.filter(function(_, element) {
    for (var d = 0; d < domains.length; ++d)
      if (domains[d] == $(element).text()) return true;
    return false;
  });
};

Then you can just say something like:

var theDivs = $('div.whatever').pickDomains('.co.uk', '.com', '.net');
+1
source

I also came across this problem several times, especially since I developed it in Prototype, where the StartsWith function exists . There is probably only a way to loop through a div and check for substrings; the code can be found on a previous similar question .

0
source

Source: https://habr.com/ru/post/1738487/


All Articles