Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inverse <li> selection using :not() and :contains()?

I want to make a live search with jQuery. Here's my code:

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

Showing <li> which contains "searched text" work properly but the second part (hiding the rest of the items) doesn't work completely.

How can I hide <li>s when I search for unrelated word?

like image 384
John K Avatar asked Dec 07 '25 11:12

John K


1 Answers

You can use jQuery.not

Solution 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>

You can use jQuery filter ( see below snippet)

Solution 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>
like image 56
Vladu Ionut Avatar answered Dec 09 '25 23:12

Vladu Ionut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!