49

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?

Josh
  • 6,688
  • 8
  • 46
  • 74
  • 12
    Just `$(".something:not(:contains('text'))")` works. Just tried on this thread: `$(".question:not(:contains('filter2134234'))")` – megawac Nov 19 '13 at 02:43
  • For the second point: "[Is there a case insensitive jQuery :contains selector?](http://stackoverflow.com/q/187537/15031)" – Jonathan Lonowski Nov 19 '13 at 02:45

3 Answers3

98

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.

BriAnna
  • 1,778
  • 12
  • 11
  • I wound up using a filter function anyway, because I needed to make the search case insensitive, and there was no simple transformation of the user's input that would make it match the text of the list items. But, I think this is the best answer I'm going to get. – Josh Nov 19 '13 at 12:05
  • I reviewed the discussion on the question http://stackoverflow.com/questions/187537/is-there-a-case-insensitive-jquery-contains-selector and I felt like it was simpler to just use a filter function than try and modify :contains to be case-insensitive. – Josh Nov 19 '13 at 12:06
  • Have a injection vulnerability, by example as input: `test)),other...` – e-info128 Oct 17 '20 at 19:27
15

Let say that you want the list of all <td> that dont contains string 'Dinesh'.(assuming Dinesh is inside name Attribute)

$('tableId > tbody > tr > td').not("[name*='Dinesh']")
JF it
  • 2,354
  • 3
  • 18
  • 29
dinesh kandpal
  • 723
  • 7
  • 15
6

Use this:

$("div:not(:contains('John'))").css("text-decoration", "underline");
Odys
  • 8,545
  • 9
  • 66
  • 108
Habrashat
  • 637
  • 6
  • 12