a
a1

Get the whole element containing or not containing some class

I have an 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 the whole element containing class a or b or c

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

And how to get all elements not containing a or b class

$(".dv:not(.a|.b)").each(function() {}); // ?how to get
+4
source share
2 answers

The thing about jQuery is that it can use your CSS skills, provided the browser is updated. If so, then the following pure CSS selectors will do the following:

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

}

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

}

The following snippet illustrates 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>
Run codeHide result
+2
source

To select a logic or:

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

To select a logic not:

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

To select everything .dv, but without .d:

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

, :

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>
Hide result
+5

Source: https://habr.com/ru/post/1685380/


All Articles