Josh Josh - 4 months ago 37
Javascript Question

jQuery "not contains" selector

The :contains() jQuery selector allows you to match find elements that contain a specified string of text. What I want to do seems related: I'm providing the user a "filter" text box that they can type in, and I have a set of list items.

I want to have all list items that do not contain the text the user entered in the textbox be hidden as they type.

I can listen for the keyup event on the textbox, but I'm not sure how to do two things:

  1. "Invert" the :contains() selector results--I want to select elements that don't match, and hide them.

  2. Make the matching case sensitive.

It's occurred to me that I could use .filter( function(index) ), but I'm wondering if I'm overthinking this--is there a way to accomplish this already with the selectors/functions built-in to jQuery?


Assuming your user's text is stored in a variable called userString:

$(':not(:contains('+ userString +'))').hide(); 

will hide all of the elements not containing that string.

Edit: If you have control over the elements in the list items, you could transform the user's text when you store it in the userString var.