Selecting elements by classes with jQuery

1

How do I select an HTML element that has only the classes I want? For example:

$('.a.b.c') -> deve retornar apenas a div1 e não todos os elementos que também possuam as classes a, b e c além de outras
<div name="div1" class="a b c"></div>
<div name="div2" class="a b c d"></div>
    
asked by anonymous 24.11.2015 / 19:20

1 answer

2

You'll have to make this selection in several steps. You could use $('[class="a b c"]') but you can have these classes in different order.

So if you do as you wrote $('.a.b.c') you will select elements that have at least these three classes. To exclude others who have even more classes you can do this:

var seletor = '.a.b.c';
var selecionados = $(seletor).filter(function (el) {
    var classes = seletor.split('.').filter(Boolean);
    return this.className.split(' ').filter(function (classe) {
        return classes.indexOf(classe) == -1;
    }).length == 0;
});

selecionados.html('eu!!');

jsFiddle: link

    
24.11.2015 / 19:33