know the number of divs that is out of other

2

I would like to know How can you get the amount of divs, in this case from the div_principal class, which are not included in the class div_global? In this case you should return value.

<div class="div_global">
    <div class="div_principal"></div>
    <div class="div_principal"></div>
    <div class="div_principal"></div>
</div>

<div class="div_principal"></div>
<div class="div_principal"></div>
    
asked by Danilo 07.01.2016 в 00:33
source

4 answers

5

You can use .not() to remove the <div> that are inside.

var divsFuera = $(".div_principal").not(".div_global .div_principal").length;
console.log(divsFuera);
.div_global {
  border: 1px solid black;
}

.div_principal {
  height: 10px;
  background: red;
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div_global">
    <div class="div_principal"></div>
    <div class="div_principal"></div>
    <div class="div_principal"></div>
</div>

<div class="div_principal"></div>
<div class="div_principal"></div>
    
answered by 07.01.2016 / 01:18
source
2
  • Count the total number of elements <div> within <div class="div_global">
  • Count the amount of <div class="div_principal"> you have and to them you add their elements <div> children.
  • Get the difference.
  •     var divG = $('.div_global div').length;
        var divP = $('.div_principal, .div_principal div').length;
        var dife = divG - divP;
    

    The variable dife has what you need.

        
    answered by 07.01.2016 в 01:10
    1

    A simpler version. In this case we look for the .div_principal direct descendants of body with the selection operator > :

    var divsFuera = $('body > .div_principal').css('background', '#00BBFF');
    
    $('#fuera').text($('#fuera').text() + divsFuera.length)
    .div_global {
      background: #F7F7F7;
      padding : 5px;
    }
    
    .div_principal {
      height: 10px;
      background: #FFBB00;
      padding: 10px;
      margin : 5px;
      border-radius : 10px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  
    <div class="div_global">
      <div class="div_principal"></div>
      <div class="div_principal"></div>
      <div class="div_principal"></div>
    </div>
    
    <div class="div_principal"></div>
    <div class="div_principal"></div>
    
    <div id="fuera"> Divs fuera : </div>
        
    answered by 02.07.2016 в 17:58
    0

    You can use this code

    $(function() {
       var divs=0;
       $(".div_principal").each(function(){
              if(!$(this).parents("div").hasClass('div_global')){
                    divs++;
              }
       });
       alert(divs);
    });
    

    you can try it on this fiddle

        
    answered by 07.01.2016 в 01:05