Selection of elements by classes with jQuery

Asked

Viewed 321 times

1

How do I select an HTML element that has only the classes I ask for? 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>
  • have you thought about using id in div?

  • This div is generated by a framework, I did not create it

  • and take the div by name? ex: $(".a.b. c[name='div1']")

1 answer

2

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

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

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: http://jsfiddle.net/pvLhdy10/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.