开发者

Find out the index of a given div in jQuery?

开发者 https://www.devze.com 2022-12-12 11:19 出处:网络
Newbie jQuery question: How do I find out what number a given div is in the DOM-tree? $(\'div.dashbo开发者_运维百科ard-module\').each( function() {

Newbie jQuery question:

How do I find out what number a given div is in the DOM-tree?

$('div.dashbo开发者_运维百科ard-module').each( function() {
    var divNumber = $(this).[DON'T KNOW WHAT TO WRITE HERE];
});

alert('This div is number ' + divNumber );

Hope it makes sense! :)


If you want to know the index of the element you are currently iterating you can use the first argument of the callback function:

$('div.dashboard-module').each(function (index) {
    var divNumber = index;
});

More info:

  • each (callback)


What are you looking for the number relative to?

If its the document, then you need

$('div.dashboard-module').each(function(){
    var divNumber = $(document).index($(this));
});

If its relative to the parent, then you need

$('div.dashboard-module').each(function(){
    var divNumber = $($(this).parent()).index($(this));
});

etc.

Comment if you've got any questions


var divNumber = $('div.dashboard-module');
alert("This div is number " + (divNumber.length-1) + ". " + $(divNumber[divNumber.length-1]).html() );
0

精彩评论

暂无评论...
验证码 换一张
取 消