JSFiddle - React, Tailwind, and code Playground
HTML
<ul class="commentlist">
<li>parent one</li>
<ul>
<li>child one</li>
<li>child two</li>
</ul>
<li>parent two</li>
<ul>
<li>child three</li>
</ul>
<li>parent three</li>
<ul>
<li>child four</li>
</ul>
</ul>
<form>
<input id="filter" type="text" />
</form>
<div id="filter-count"></div>
JavaScript
$(document).ready(function () {
$("#filter").keyup(function () {
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(),
count = 0;
if (!filter) { // hide is no text
$(".commentlist li").hide();
$("#filter-count").text("Number of Comments = " + count);
return;
}
var regex = new RegExp(filter, "i"); // Create a regex variable outside the loop statement
// Loop through the comment list
$(".commentlist li").each(function () {
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(regex) < 0) { // use the variable here
$(this).hide(); //**here I want to put condition that checks for parent element and if its parent then it should not fadeout the its child element**
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
$("#filter-count").text("Number of Comments = " + count);
});
});