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

What steps are involved in incorporating dynamic pagination in PHP using this particular snippet of code?

I am looking for a way to display a list of numbers from 1 to 1000 in a single line with the ability to scroll. However, I need to exclude both "Prev" and "1" from this list. How can I achieve this? Below is the code snippet that I currently have: echo ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...

What is the best method for resetting the CSS style of a specific DOM subtree?

While working on a Chrome Extension, I encountered a problem where an HTML subtree and CSS style sheet injected into the original page were being affected by the original CSS. Despite my attempts to override the styles, it seemed unfeasible to manually set ...

How to eliminate the unnecessary gap between rows in a Vue div displayed as a grid

I have recently started working with Vue and in my current project, I encountered a challenge where I needed to display 2 players in each row within a div. To achieve this, I utilized the display: grid; CSS property on the playerDiv id. However, I am facin ...

Only display entries with no content

When attempting to filter data from a search, all results are being displayed on the submit button even when entering 1, 2, or 3. Here is my code below. Please let me know if I am making a mistake somewhere. ...

Tips for updating the color of buttons after they have been selected, along with a question regarding input

I need help with a code that changes the color of selected buttons on each line. Each line should have only one selected button, and I also want to add an input button using AngularJS ng-click. I am using AngularJS for summarizing the buttons at the end ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Suggestions for rectifying the calculation script to include the price, a phone number, 2 digits, and integrating a textfield for cost

I have developed a script that calculates prices, phone numbers, and extracts the last 2 digits from the phone number. In my website, the price is displayed through a select option. However, I am facing an issue where the cost does not automatically updat ...

The situation arose where Next.js could not access the cookie due to

Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions. In this component, I am trying to fetch user data from my ...

The information is not being shown. Error: API expression GET is not possible

import express from 'express'; import data from './data'; const app = express(); app.get("/api/products", (req, res) => { res.send(data.products); }); app.listen(5500, () => {console.log("The server has been successfully s ...

Exploring the dissimilarity among npm run dev and the parcel index.html

I have been using parcel index.html to set up a local development server, bundling, and hot module replacement. However, I recently learned that npm run dev can do something similar. This has left me wondering: What are the distinctions between the two me ...

How can we initiate an AJAX request in React when a button is clicked?

I'm fairly new to React and I'm experimenting with making an AJAX call triggered by a specific button click. This is how I am currently using the XMLHttpRequest method: getAssessment() { const data = this.data //some request data here co ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

Struggling with PHP variables and AJAX JavaScript

Hey everyone, I've made some edits and have a new question regarding a similar issue. On test.php in my Apache server, I have a PHP script that connects to a database and retrieves data from a table. <?php $con = mysqli_connect("localhost", "user" ...

Why does Math.max.apply not prioritize the first parameter?

function findSmallestNumber(numbers){ return Math.min.apply(Math, numbers); } This code sets the context to be the Math object. However, this is not required because the min() and max() methods will still function properly regardless of the specified co ...

Utilize Angular to transform a standard text string within a JSON object into a properly formatted URL

Welcome to my first Stack Overflow question! I usually find the answers I need on my own, but this time I could use some guidance as I delve into Angular. I have a directive that pulls the name and URL from a JSON object and generates HTML with the name a ...

pattern validation using a regular expression

I am just starting to learn about regular expressions. In my current project, I am allowing users to input amounts in both shorthand and full digit formats using a material UI TextField component. Here are some examples of the input formats: 400k - short ...

Creating an HTML table with colspan and rowspan using ng-repeat from a deeply nested JSON dataset

I'm working on creating a table layout shown in the attached image: Composite Class Routine Check out my progress so far in this Plunker demo: https://plnkr.co/edit/4WiWKDIM2bNfnmRjFo91?p=preview The JSON data I'm using is as follows: $scope. ...

Is it possible to share a MySQL connection for cross-module usage in Node/Express by utilizing promise-mysql?

Currently, I am trying to import and utilize a database module within one of my controllers. Despite successfully establishing the initial connection, I am encountering an error when accessing any of my routes through the browser: "Cannot read property ...