0

I would like to search for all list items and display only those that contain a certain phrase.

I however have placed the contents in a span. Meaning that my list looks a bit like this:

<ul class="sortable">
<li><span>search keywords here</span>A lot of code possibly here. Some divs and some other elements</li>
</ul>

And I would like more or less use the following code to filter.

var filter = $('#search_page_query').val(), count = 0;    

$(".sortable li").each(function () {

    if ($(this).text().search(new RegExp(filter, "i")) < 0) {
        $(this).fadeOut();


    } else {
        $(this).show();
        count++;
    }
});

This however would only work if the list item contains directly the search keywords.

That's not the case. I should search the list item with something like:

$(this + 'span').text()

But this is of-course incorrect. But I have no clue how to access the span contents correctly. I hope that anyone could shed me a light on how it's done.

Thanks In Advance


Solved by @RameshKithsiriHettiArachchi

The solution is

Instead of :

$(this).text()

use :

$(this).children('span').text()

Full code :

var filter = $('#search_page_query').val(), count = 0;    

$(".sortable li").each(function () {

    if ($(this).children('span').text().search(new RegExp(filter, "i")) < 0) {
        $(this).fadeOut();


    } else {
        $(this).show();
        count++;
    }
});
Alex
  • 1,223
  • 1
  • 19
  • 31

1 Answers1

0

to select a children of current DOM Element use $(this).children() function.

https://api.jquery.com/children/

  • There are many other ways to achieve this, and you might be better off using `$(this).find(">span").text()` or `$(">span", this).text()` rather than `.children()`. But it's mostly micro managing. See here for more info: https://stackoverflow.com/a/27234084/2181514 – freedomn-m Feb 05 '18 at 11:15