Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 398
DeLe Avatar asked Mar 08 '23 02:03

DeLe


2 Answers

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>
like image 143
Koby Douek Avatar answered Mar 28 '23 11:03

Koby Douek


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>
like image 30
Manngo Avatar answered Mar 28 '23 11:03

Manngo