Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 922
Josh Avatar asked Nov 19 '13 02:11

Josh


People also ask

How do you check does not contain jQuery?

Use the :not() CSS selector.

How use contains in jQuery?

jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

How do I check if a div contains a text?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

Is jQuery selector case sensitive?

jQuery attribute value selectors are generally case-sensitive.


3 Answers

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.

like image 174
BriAnna Avatar answered Oct 18 '22 06:10

BriAnna


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']")
like image 20
dinesh kandpal Avatar answered Oct 18 '22 07:10

dinesh kandpal


Use this:

$("div:not(:contains('John'))").css("text-decoration", "underline");
like image 7
Habrashat Avatar answered Oct 18 '22 07:10

Habrashat