DeLe
DeLe

Reputation: 2480

Get all element contain or not some class

I have html structure like

<div class="dv a">a</div>
<div class="dv a">a1</div>
<div class="dv b">b</div>
<div class="dv b">b1</div>
<div class="dv c">c</div>
<div class="dv c">c1</div>
<div class="dv d">d</div>
<div class="dv d">d1</div>

How can i get all element contain a or b or c class

$(".dv").each(function(){}); /// ? how to get

And how to get all element not contain a or b class

$(".dv:not(.a|.b)").each(function() {}); // ?how to get

Upvotes: 4

Views: 94

Answers (2)

Manngo
Manngo

Reputation: 16301

The thing about jQuery is that it can take advantage of your skills in CSS, provided that the browser is up to date. If it is, then the following pure CSS selectors will do the job:

.dv.a, .dv.b, .dv.c {           /*  Matching Ones: */

}

.dv:not(.a):not(.b):not(.c) {   /*  Non Matching Ones: */

}

The following snippet will illustrate this:

.dv.a, .dv.b, .dv.c {
  color: red;
}

.dv:not(.a):not(.b):not(.c) {
  border: thin solid green;
}
<div class="dv a">a</div>
<div class="dv a">a1</div>
<div class="dv b">b</div>
<div class="dv b">b1</div>
<div class="dv c">c</div>
<div class="dv c">c1</div>
<div class="dv d">d</div>
<div class="dv d">d1</div>

Upvotes: 2

Koby Douek
Koby Douek

Reputation: 16675

To select with or logic:

$( ".a, .b, .c" )

To select with not logic:

$( "div:not(.a, .b)" )

To select all .dv but without .d:

$( ".dv:not(.d)" )

Here's a snippet that counts all logics with the selectors above:

var orCount = $( ".a, .b, .c" ).length;
var andCount = $( "div:not(.a, .b)" ).length;
var notdCount = $( ".dv:not(.d)" ).length;

console.log('or logic count = ' + orCount);
console.log('and logic count = ' + andCount);
console.log('not d logic count = ' + notdCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dv a">a</div>
<div class="dv a">a1</div>
<div class="dv b">b</div>
<div class="dv b">b1</div>
<div class="dv c">c</div>
<div class="dv c">c1</div>
<div class="dv d">d</div>
<div class="dv d">d1</div>

Upvotes: 5

Related Questions