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:
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?
Use the :not() CSS selector.
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).
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.
jQuery attribute value selectors are generally case-sensitive.
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.
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']")
Use this:
$("div:not(:contains('John'))").css("text-decoration", "underline");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With