Reputation: 246
Before I start, this is a kind of 'part 2' of Search for divs that contain specified text
Hey. I got a list of divs, and each has several divs (to style), it looks like this:
<body>
<div class='divlist'>
<div>
<div>abc</div><div>def</div><div>ghi</div>
</div>
</div>
</body>
In the body
tags I've also got a search (<input type='text' id='search' />
)
and my jquery:
$('#search').on('input', function(){
var text = $(this).val();
$('.divlist div').show();
$('.divlist div:not(:contains(' + text + '))').hide();
});
Now, if I search for abc
it will remove the div containing def
and ghi
, although the search matched the div (the one with the abcdefghi inside).
So:
How would I make a search function that removes the main div if nothing matches (for instance, j
) and show all of the divs inside the div containing the other divs no matter how many divs match.
Thanks in advance.
ps. if someone knows a better title, feel free to change it
Upvotes: 1
Views: 91
Reputation: 144709
Instead of filtering all the div
elements, filter the .divlist
elements:
$('.divlist:not(:contains(' + text + '))').hide();
Or their immediate div
children using child selector:
$('.divlist > div:not(:contains(' + text + '))').hide();
You can also use .filter()
method which is more efficient than expensive :not(:contains())
selector:
$('.divlist > div').hide().filter(function() {
return $(this).text().indexOf(text) > -1;
}).show();
Upvotes: 1