What is the best approach to reverse the selection of <li> elements by utilizing :not() and :contains

I am looking to implement a live search feature using jQuery. Below is the code snippet I have written:

$("#searchInput").on("keyup", function () {
        var searchTerm = $("#searchInput").val();
        $('li:contains("' + searchTerm + '")').show().siblings(':not(li:contains("' + searchTerm + '"))').hide();
});

The code successfully shows the <li> elements containing the searched text, but the second part - hiding the rest of the items - does not work as expected.

Is there a way to hide <li> elements when searching for unrelated words?

Answer №1

Utilize jQuery.not

Method 1

$("#searchInput").on("keyup", function() {
  var searchTerm = $("#searchInput").val();
  $("ul li").show().not($('li:contains("' + searchTerm + '")')).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchInput" />
<ul>
<li>
  Hello
</li>
<li>
  World
</li>
<li>
  List 1
</li>
<li>
 Word
</li>
<li>
  Another Li
</li>
</ul>

Consider using jQuery filter ( check snippet below)

Method 2

$("#searchInput").on("keyup", function() {
  var searchTerm = $("#searchInput").val();
  $("ul li").show().filter(function() {
    return $(this).text().indexOf(searchTerm) == -1
  }).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchInput" />
<ul>
<li>
  Hello
</li>
<li>
  World
</li>
<li>
  List 1
</li>
<li>
 Word
</li>
<li>
  Another Li
</li>
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ng-class condition is in flux, however, the new style is not being

Attempting to modify the background of the pane in an Ionic application based on the condition of the ng-class as shown. Changing the condition in the code and refreshing the page manually works correctly, but updating the condition from user input does ...

Error encountered while submitting ajax request to server

When I click a button, a function is triggered with the argument insertSongPlay(newSong.songID);. After logging the value of newSong.songID, which is 90 as desired, an ajax call is made: function insertSongPlay(songID) { $.ajax ({ type: " ...

What is the best way to customize the style using a CSS class?

Is it possible to alter a specific style with a CSS class using jQuery or JavaScript? For example, if the HTML looks like this: <tab> <a class="anchor">a</a> </tab> And the CSS looks like this: a {border:1px} .anchor {color: ...

What causes the accordion class to activate panels with varying names?

Why are some of my accordions triggering other accordions when they have different names? I've been working on resolving the issue where opening the second accordion in the second, third, or fourth panel closes the second accordion in the first panel ...

Difficulty encountered in aligning items within neighboring table cells vertically

Currently, I am facing a styling issue with a few table rows. In this particular screenshot: https://i.sstatic.net/FcmJW.png The cells in the blue and red circles are part of a table row (with a height of 50px). Both are set to "vertical-align:top". The ...

Tips for modifying a HTML table to switch one column with 60 rows to three columns with 20 rows dynamically

Need assistance with separating a dynamically loaded single-column HTML table of 60 rows into three columns of 20 rows each using jQuery in JSP. For example, starting with the loaded table: test 1 test 2 test 3 test 4 test 5 test 6 test 7 test 8 test 9 t ...

Harness the power of multiple backgrounds with just one CSS style!

I'm exploring a way to incorporate multiple images as backgrounds into my website design. For instance, having a car image on the index page and a notepad image on the about me page. My attempt involved using the following code: body { back ...

The error message "THREE is not defined" occurred while running mocha tests for a

I am attempting to execute a basic Mocha unit test for code that utilizes the Vector3 class from THREE.js: import {Vector3} from 'three'; const a = new Vector3(0, 0, 0); When running this test using Mocha (specifically mocha-webpack, with webpa ...

PHP 500 (Internal Server Error) - An unexpected non-numeric value has been encountered

Currently, I am facing an issue while trying to implement an autocomplete search input using jQuery and Laravel. The problem arises when the user types at least 2 letters into the search input field: GET http://proj.test/autocomplete-search?term=ca 500 (I ...

Issue with Browsersync functionality in Docker

My Node.js app is facing an issue with Gulp, Browsersync, and Docker. When I run gulp watch locally, everything functions correctly. However, when I utilize docker-compose up, I encounter an error Cannot GET / The Browsersync UI on port 3001 is operat ...

Attempting to apply a minimum width to a th element using the min-width property

I'm trying to set a width for the second th element in this table, but it's not working as expected. <th style="min-width: 50px"> Date from </th> Can anyone provide assistance with this issu ...

Rearranging the order of Div elements within a main container using JavaScript DOM manipulation

How can I move elements within a div from the start to the end in the same div, for example, changing the order from 1-2-3 to 2-3-1? My code: const cards = document.querySelectorAll(".card"); const firstCard = document.querySelectorAll(".card")[0].inne ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

Enhancing the styling of checkboxes using CSS and Javascript

My Javascript skills have been put to the test with a simple code snippet that customizes checkboxes by hiding them and using background images in CSS to display checks and unchecks. It's a neat trick, but I'm wondering if it's HTML/CSS comp ...

Countdown timer that counts down in reverse when the browser is minimized

I am currently working on a JavaScript project where I have implemented a countdown timer in seconds. Once the timer hits zero, it triggers a specific function. The timer functions correctly, however, if the browser enters sleep mode or is minimized, the ...

Retrieve file server domain using JavaScript or jQuery

I'm trying to extract the domain name without the "http(s)://www." from a file link. For example, if the script returns "example.com", I want it to parse through links like "http://www.example.com/file.exe" or "https://example.com/folder/file.txt#some ...

Problem saving videos when using the right-click function

Hello, I am currently working on retrieving videos from a database, but I have encountered an issue with the video saving option. When a user right-clicks on the video, they are able to save it in their system's storage. What I would like to achieve ...

Distributing actions within stores with namespaces (Vuex/Nuxt)

I'm encountering an issue with accessing actions in namespaced stores within a Nuxt SPA. For example, let's consider a store file named "example.js" located in the store directory: import Vuex from "vuex"; const createStore = ...

Tips to prevent browser from freezing while creating a large number of HTML elements

I am currently utilizing Selection.js to develop a customizable grid on my website. To make this work effectively, I need a specific number of div elements to establish the selectable area. In my scenario, I generate all the divs using a for loop and then ...

I can retrieve my information from the controller by utilizing Ajax

I am currently developing a project in asp.net mvc4. Specifically, I am working on a form that includes a Select element containing a list of contacts: <select id="choix_contact"> <option>Choose a contact</option> @if (ViewBa ...