Take the 2-minute tour ×

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


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.

share|improve this question
add comment

4 Answers

You can use the filter method to check the content:

  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();
share|improve this answer
+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
add comment

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

    if ($(this).text().match(/^\.(com|net|co\.uk)$/)) {
        // ...
share|improve this answer
add comment

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');
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer


