Amit Singh
Amit Singh

Reputation: 2275

Get number of elements with same class inside a div tag

I'm trying to find the number of divs with class name component ui-draggable dropped inside a particular div.

Here is the respective HTML code:

<div id="tabs-1" aria-expanded="true" aria-hidden="false">
  <div class="drag-drop-box ui-droppable">
    <div class="component ui-draggable dropped">
      <div class="product-view" >
         <a href="#"><span>C</span> us-east-1c</a>
      </div>
    </div><div class="component ui-draggable dropped">
      <div class="product-view">
         <a href="#"><span class="img-product">
         <img alt="" src="img/product_item/1.png"></span> image-11</a>
     </div>
   </div>
  </div>
 </div>

And this is the respective jQuery Code:

var getid = $('div[aria-hidden="false"]').attr('id');
var clone_nums = $('#'+getid + '> div ').find('.component ui-draggable dropped').length;
alert(clone_nums

But alert always pops-up zero. Can anyone guide me what's wrong here? Thanks

Upvotes: 2

Views: 2036

Answers (3)

Alexandru Chichinete
Alexandru Chichinete

Reputation: 1183

var clone_nums = $('div[aria-hidden="false"]').find('div.component.ui-draggable.dropped').length;


For an element with multiple classes join the name of classes using "."(class selector) between them and don't use spaces.

Upvotes: 1

Kiran
Kiran

Reputation: 20313

Try this:

$(document).ready(function(){
var getid = $('div[aria-hidden="false"]').attr('id');
var clone_nums = $('#'+getid + '> div ').find('.component.ui-draggable.dropped').length;
alert(clone_nums);
});

DEMO

or

$(document).ready(function(){
   var clone_nums = $('div[aria-hidden="false"] > div').find('.component.ui-draggable.dropped').length;
alert(clone_nums);
});

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

You can use .has() like

var $div = $('div[aria-hidden="false"]');
var clone_nums = $div.has('.component.ui-draggable.dropped').length;
  • get all divs with aria-hidden="false"
  • then filter in only those which is having a descendant with classes component ui-draggable and dropped
  • of course you need to execute the script after the target elements are loaded in the dom tree

Upvotes: 1

Related Questions