简体   繁体   中英

div not contains any string from an Array - Jquery

I want to check if a div not contains string from an array. lets say the array is:

var vals = ["a","b","c"]

I want to hide all the divs that don't contain any of these strings.

        <script type="text/javascript">
          var vals = ["a","b","c"];
           $("div").hide();
          $(document).ready(function () {
             for (index = 0; index < vals.length; ++index) {    
                $("div").hide();     
                $("div p:contains(vals[index])").parent('div').show();
             }   
          });
        </script>

DEMO http://jsfiddle.net/GS8QD/5/

var vals = ["a", "b", "c"];
var $divs = $('.container div');
$divs.each(function () {
    var $currDiv = $(this);
    $.each(vals, function (index, value) {
        if ($currDiv.is(':contains(' + value + ')') && $currDiv.is(":visible")) {
            $currDiv.hide();
        }
    });
});

Explanation: Loop through each div from the collection of divs & inside the loop have another loop which loops through each value in the array. Now check if the div contains the value & then hide it.

If you want only the divs to show that contain a, b or c you can do this -

var vals = ["a", "b", "c"];

$('div:not(:contains('+vals[0]+'),:contains('+vals[1]+'),:contains('+vals[2]+'))').hide();

http://jsfiddle.net/jayblanchard/9SJ2h/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM