5

Possible Duplicate:
jQuery multiple class selector

I have an input field '#q' where a user can type a search query and returns a set of list items whose classes match it.

function queryData() {
   q = $('#q').val();
   q = q.toLowerCase();
   var qs = q.split(' ');
   $('.item').fadeOut(300);
   for (n in qs)        {
   $("li[class*='" + qs[n] + "']").fadeIn(1000);
                }
} 
<li class="apple"></li> <li class="apple banana"></li> <li class="banana"></li>

I'm not an expert so the code above may appear crude. So far, the code above is only able to display li's whose classes match the query regardless of the number of words in the query. So, if I type in "apple banana", any li with apple or banana as class will fadeIn(). How do I edit this function so that only the li's with BOTH apple and banana in its class will fadeIn()?

Community
  • 1
  • 1
druesome
  • 155
  • 1
  • 7
  • What exactly do you want? the text "apple banana" to match only the middle li, or for it to match all 3? how about the text "banana apple"? should it match any of them? As a side note: I think most people find reading code easier when variables have more than one letter names. Descriptive variables improve code quality I think. Also, you can use the "." selector for class. So "li ."+qs[n] might be a bit easier to read if it is equal (i don't know what the star does after class) – Andy Groff Oct 20 '10 at 03:39
  • Sorry, I meant match both apple AND banana. Edited my message. – druesome Oct 20 '10 at 03:41
  • FYI - You can use .hasClass() to test if the element has a specified class. – mellowsoon Oct 20 '10 at 03:48

2 Answers2

3

How can I select an element with multiple classes?

Try this too:

function queryData() {
    $('.item').fadeOut(300);
    $("li."+
     (
      $('#q')
      .val()
      .toLowerCase()
      .split(/\s+/)
      .join('.')
     )
    ).fadeIn(1000);
}
Community
  • 1
  • 1
Michael MacDonald
  • 708
  • 1
  • 6
  • 24
0

I'd use the list of terms to build a single query, eg

var qs = q.split(' ');
for (n in qs) {
    qs[n] = 'li.' + qs[n];
}
$(qs.join(', ')).fadeIn(1000);

This will fade in any "li" with any class entered.

The jquery-multiple-class-selector referenced only matches elements containing all classes

EDIT: Just saw your edit (require all classes). In that case, try

$('li.' + q.replace(' ', '.')).fadeIn(1000);
Phil
  • 157,677
  • 23
  • 242
  • 245