简体   繁体   中英

Selecting multiple divs with same class

I have a HTML structure how this:

<div class="className"></div>
<div class="className"></div>
...
<div class="className"></div>

I am trying to select these elements with jQuery. For that, I'd like to know if it's possible target these items within a loop, where N is the number of divs . In the first loop I want to target the first div , in the second loop the second div , etc...

for (var i = 0; i < N; i++) {
    $(".className")...
};

Also, it's possible to know the number of divs with the same class with jQuery?

The $(...) notation returns an array-like object, meaning you can refer to a specific element through its index:

$(".className")[i]...

However it's worth noting that jQuery has a couple of its own looping methods, including each() and map() which can probably be used instead of a native for loop in this case:

$(".className").each(function() {
    var current_element = $(this);
});

jQuery objects implement JavaScript's length property, so you can use this to count the number of matching elements:

var number_of_divs = $(".className").length;

To satisfy the requirements your question asks for:

var elems = $('.className'),
    N = elems.length;

for (var i = 0; i < N; i++)
    elems[i]...

Try this,

$('.className').each(function(){
    // your logic
});

To know total no. of div with same class,

var totalDivs = $('.className').length;

You can know the length

$('.className').length;

The size size();

$('.className').size(); // Deprecated since jQuery 1.8 though 

Or just use each

$('.className').each(function(){  // code    });

To loop you can use .each()

$(".className").each(function(){});

And to get the total number you just have to use the property length .

var numOfDiv = $(".className").length;

U need each() function know.

   $(".className").each(function(Integer index, Element element){
.......
   });

http://api.jquery.com/each/

$.each($('.className'),function(index,value){
console.log(value);
})
console.log('LENGTH : '+$('.className').length);

When running $('.className') , you are actually creating a list of all elements with that specific class, wrapped in a jQuery object. You could run .each() on this object to iterate all elements, like this:

$('.className').each(function (index, element) {
  // this refers to the current element here (not wrapped in a jquery object)

});

use this code:

var elems = $('.className');
N = elems.length; // this gives no. of divs
for (var i = 0; i < N; i++)
{
    $(elems[i])...  // by using this you can point to each div with same class name
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM