简体   繁体   中英

jQuery select if multiple elements has the same class

Example HTML:

<div class="elem-1"></div>
<div class="elem-2"></div>
<div class="elem-2"></div>
<div class="elem-3"></div>
<div class="elem-4"></div>
<div class="elem-4"></div>
<div class="elem-4"></div>

Needed: How can I select the div's which has "elem-2"s and "elem-4"s with jQuery selectors? (multiple elements has same class)

您可以使用,来分隔不同的选择:

$(".elem-2, .elem-4")
$('.elem-2, .elem-4').hide() // or any other jquery method

顺便说一下,它不是jQuery选择器,而是CSS选择器,请参阅本文以获取解释

selector will be given the value that you desire

http://jsfiddle.net/mMEN5/1

var selector = $();

var list = $('[class]').toArray().reduce(function(p, e){
    p = p || {};
    var classes = $(e).prop('class').split(/\s/);
    $.each(classes, function(i,c){
        p[c] = p[c] || [];
        p[c].push(e);
    });
    return p;
}, {})

for (el in list) if (list[el].length > 1) selector=selector.add(list[el]);
​

Even though you have asked for css selector, we can also use the attributeStartsWith selector

I will just mention the selector usage. you can use to for any internal DOM chnage

alert($('div[class^="elem-2"], div[class^="elem-4"]').length);

here i have used .length just to give a correct count. Use can use above with id attributes also.

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