3

I have a series of <div/>'s as follows:

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

How do I select just the divs containing .co.uk, .com, .net.

If I use:

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

This causes the .gb.com and .uk.com divs to be selected as well.

Kev
  • 118,037
  • 53
  • 300
  • 385

4 Answers4

5

You can use the filter method to check the content:

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

You might still want to weed out as many elements as possible in the selector to reduce the number of elements that the filter function has to check. Even if the contains pseudo class can't make an 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';
})
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • +1 Funny, you wrote exactly similar code sample with me, including variable names! Man, you've got nice coding style! ;) I will delete my reply. – jholster Mar 25 '10 at 13:26
  • Strange, this seems to just return one div (the first match). I read up on the .filter() function and this should work, but it doesn't. – Kev Mar 25 '10 at 15:33
  • @Kev: I tested both versions, and they do return three elements. (There was just one back tick in the second version that I had to change to an apostrophe to get it to work.) – Guffa Mar 25 '10 at 16:52
1

Your best bet is to iterate through the divs with .each() and check for the contents in the callback by checking $(this).text():

$('div').each(function() {
    if ($(this).text().match(/^\.(com|net|co\.uk)$/)) {
        // ...
    }
});
reko_t
  • 55,302
  • 10
  • 87
  • 77
1

I'd do it 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');
Pointy
  • 405,095
  • 59
  • 585
  • 614
0

I was facing that problem, too, several times, especially since I was developing in Prototype where a StartsWith function exists. There's probably only the way of looping through divs and checking for substrings, code can be found on previous similar question.

Community
  • 1
  • 1
Paul
  • 8,974
  • 3
  • 28
  • 48