Find out the index of a given div in jQuery?

New jQuery question:

How to find out what number of a given div is in the DOM tree?

$('div.dashboard-module').each( function() {
    var divNumber = $(this).[DON'T KNOW WHAT TO WRITE HERE];
});

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

Hope this makes sense! :)

+3
source share
3 answers

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

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

Additional Information:

+4
source

What are you looking for relative numbers?

If this is a document, you need to

$('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));
});

and etc.

Comment if you have questions

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

Source: https://habr.com/ru/post/1724037/


All Articles