herrsaidy
herrsaidy

Reputation: 91

Check Elements with the same Class and add new Element

I have multiple Divs with the same Class, when all Divs have the Class "hideaddress" then I insert an new Div. But when one of this Divs has not the Class "hideadress" I don't want to show the new Div. But it does not work. How can I change this??

if ($('div').hasClass('hideaddress')) {
  $('<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address">new adress</div>').insertBefore('div.address:nth-child(1)');
}
.hideaddress {
  opacity: 0.3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">1</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">2</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">3</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">4</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">5</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address showaddress">6</div>

Fiddle

Upvotes: 1

Views: 59

Answers (1)

Jai
Jai

Reputation: 74738

Instead of $('.hideaddress').length === $('.address').length to check if the common class name is exactly equal to the divs exists:

if ($('.hideaddress').length === $('.address').length) {
  $('<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address">new adress</div>').insertBefore('div.address:nth-child(1)');
}
.hideaddress {
  opacity: 0.3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">1</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">2</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">3</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">4</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address hideaddress">5</div>
<div class="col-lg-3 col-md-6 col-sm-6 col-xs-12 address showaddress">6</div>


This can also be checked:

if ($('.showaddress').length) { // it will check if this div exists.

Upvotes: 2

Related Questions