JQuery selects items with multiple classes

I need to select all elements containing multiple classes. Class names don't matter, I just need to select any elements with two or more.

What will the jQuery selector look like for this?

+3
source share
5 answers

This should select all elements with more than two classes.

$('*').filter(function() { return this.className.trim().split(/\s+/).length > 1; }).foo('bar'); 
+8
source
 $('[class*=" "]') 

Returns all tags with a space in the class attribute.

+3
source

Another understanding leads me to a better solution (my apologies for your conclusion):

Demo

 (function($){ $.expr[':'].classes = function(o,i,m,s){ var c = o.className.match(/\s*(.*)\s*/)[0].split(/\s+/).length; // Hard [fixed] limit // :classes(N) if (/^\d+$/.test(m[3])) { var n = parseInt(m[3], 10); return o.className.split(/\s+/).length == n; } // Expression: // :classes(>N) :classes(>=N) // :classes(>N) :classes(<=N) else if (/^[<>]=?\d+$/.test(m[3])) { var e = m[3].match(/^[><]=?/)[0], n = m[3].match(/\d+$/)[0]; switch (e){ case '<': return c < n; case '<=': return c <= n; case '>': return c > n; case '>=': return c >= n; } } // Range // :classes(4-6) else if (/^\d+\-\d+$/.test(m[3])) { var ln = parseInt(m[3].match(/^(\d+)/)[0], 10), hn = parseInt(m[3].match(/(\d+)$/)[0], 10); return ln <= c && c <= hn; } // all else fails return false; }; })(jQuery); 

Updated . Added additional flexibility regarding the argument you can provide. Now you have the following options (replacing N and M with numbers):

  • :classes(N)
    Finds elements with exactly N classes
  • :classes(<=N)
    Finds items with N or fewer classes
  • :classes(<N)
    Finds items with less than N classes
  • :classes(>=N)
    Finds items with N or more classes
  • :classes(>N)
    Finds items with more than N classes
  • :classes(NM)
    Finds elements whose class numbers fall between N and M
+2
source

The following code will first select all elements with a space in the class attribute. We could just do $ ('*'), as Blender suggests, but this is less efficient since it initially selects ALL elements on the page, and not just those that are viable candidates (i.e., have a place in the class name).

Also, those cases are considered when there is only one class, but the class attribute has a space in it (this is done using the jQuery $ .trim () method for the class attribute before it is split). Blender does not solve this situation.

 $(function(){ var div = $('div[class*=" "]').filter(function(){ var clsArray = $.trim(this.className.split(' '); return clsArray.length > 1; }); div.css('background','yellow'); }); 

Real-time example: http://jsfiddle.net/udBZy/3/

+1
source

It works just like regular CSS

 $('.class1.class2') // will select elements with both classes 
0
source

All Articles