I'm working on a text search functionality and would like to only display particular elements of the DOM: When a user types in a search term only the divs with class='accordion' and their children, grandchildren etc. should be shown that include the search term in their grand-child's text. I tried the following and the result was, that no elements were shown whenever a search term was entered.
$('#search-criteria').on('keyup', function() {
var g = $(this).val().toLowerCase();
$('.panel-info').each(function() {
var s = $(this).text().toLowerCase();
if (s.indexOf(g) !== -1) {
$(this).parentsUntil('.accordion').show();
$(this).parentsUntil('.accordion').addClass('sh');
}
else if ($(this).hasClass('sh') === false && (s.indexOf(g) === -1))
{
$(this).parentsUntil('.accordion').hide();
}
});
});
Before I had also tried this instead of the if/else, which seems much more elegant, but didn't work either:
$(this).parentsUntil('.accordion')[ s.indexOf(g) !== -1 ? 'show' : 'hide' ]();
Please find the fiddle here jsfiddle.net/2vvwZ