简体   繁体   中英

jQuery Selecting Elements That Have Class A or B or C

I working on something where I need two functions.

1 - I need to look at a group of children under the same parent and based on a class name, "active", add that element's ID to an array.

['foo-a','foo-b','foo-d']

2 - I then iterate through all the children in another parent and for each element I want to find out if it has any class name that match the ids in the array.

Does this element have class foo-a, foo-b or foo-d?

For the first part, I'd use map and get :

var activeGroups = $('#parent .active').map(function() {
    return this.id;
}).get();

This gives you an array of id values (say, ['foo-a', 'foo-d'] ). You can then make a selector like .foo-a, .foo-b, .foo-c (the multiple selector ) using join :

var activeSelector = '.' + activeGroups.join(', .');

This makes a valid jQuery selector string, eg '.foo-a, .foo-d' . You can then use this selector to find the elements you want using find :

var activeEls = $('#secondParent').find(activeSelector);

You can then do whatever you need to with activeEls .

var active = $("#foo").find(".active").map(function() {
    return this.id;
}).get();

$("#anotherParent *").each(function() {
   var that = this;
   var classes = $(this).attr("class");
   if(classes.indexOf(" ") !== -1) {
       classes = classes.split(" ");
   } else {
       classes = [ classes ];  
   }
   $.each(classes, function(i, val) {
       if($.inArray(val, active)) {

           // this element has one of 'em, do something with it
           $(that).hide();
       }
   });
});

There's always .is('.foo-a, .foo-b, .foo-d') . Or if you actually just wanted to select them, instead of iterating and deciding for each element, $('.foo-a, .foo-b, .foo-d', startingPoint) .

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