: contains for a few words

I am using the following jQuery

var etag = 'kate' if (etag.length > 0) { $('div').each(function () { $(this).find('ul:not(:contains(' + etag + '))').hide(); $(this).find('ul:contains(' + etag + ')').show(); }); }​ 

towards the next HTML

 <div id="2"> <ul> <li>john</li> <li>jack</li> </ul> <ul> <li>kate</li> <li>clair</li> </ul> <ul> <li>hugo</li> <li>desmond</li> </ul> <ul> <li>said</li> <li>jacob</li> </ul> </div> <div id="3"> <ul> <li>jacob</li> <li>me</li> </ul> <ul> <li>desmond</li> <li>george</li> </ul> <ul> <li>allen</li> <li>kate</li> </ul> <ul> <li>salkldf</li> <li>3kl44</li> </ul> </div> 

in principle, if etag has one word, the code works fine and hides those elements that do not contain etag. My problem is that when etag is a few words (and I have no control over it. It exits the database and may be a combination of several words separated by a char space), then the code does not work.

Is there any way to achieve this?

+4
source share
4 answers

This filter checks if any of the words in a given string matches the text of an element.

 jQuery.expr[':'].containsAny = function(element, index, match) { var words = match[3].split(/\s+/); var text = $(element).text(); var results = $.map(words, function(word) { return text === word; }); return $.inArray(true, results) !== -1; }; 

Show and hide as:

 $('ul').hide(); $('li:containsAny(john kate)').parents('ul').show(); 

See an example here .

+5
source

You can turn this into a function that accepts any number of words separated by a character, for example:

 function filter(words) { var uls = $('div ul').hide(); $.each(words.split(' '), function(i, v) { uls = uls.filter(':contains(' + v + ')'); }); uls.show(); } //sample call var etag='kate clair' filter(etag); 

Here you can see a working demo.

This finds the <ul> elements containing all the words in the given string.

+3
source

Another approach:

 var etag='Some text from server'; if (etag.length > 0) { $('div ul').each(function () { var el = $(this); // Local reference (el.html() === etag) ? el.show() : el.hide(); }); }​ 
+1
source

A slightly different approach - try the following:

  var etag='kate test blah'; var tags = etag.split(' '); $('div ul').each(function () { var list = $(this); list.hide(); list.children('li').each(function() { var item = $(this); if ($.inArray(item.html(), tags) >= 0) list.show(); }); }); 

It is written in the browser, so I'm sorry if there are any errors!

- change -

Actually, I re-read the question, and this code will not work. You need to first determine the behavior: should the list contain all the tags or only one of the tags that will be shown?

- change 2 -

Code updated. The view is inefficient, but it must do the job.

0
source

Source: https://habr.com/ru/post/1310635/


All Articles