views:

536

answers:

2

Hi,

I am new to jQuery.

I am having a variable increment in my code which shows how many divs inn mne of the panel.

I want to iterate through those divs to get the properties of the labels, input type ,size everything inside each div.

Starting from 1, i want to iterate up to increment .. How can i do so in JQUery? Please give me a suggestion.

+2  A: 

If you want to iterate through all divs in a panel in JQuery then the easiest way would be to simply do the following:

$("#panel div").each(function() { 
  // $(this) refers to the div
}

If you want to limit this to the first N divs then there are numerous ways to do this:

$("#panel div:lt(" + (N+1) + ")").each(function() { 
  // limits to the only those div's less than N+1.
}
samjudson
+2  A: 

I would go along with what samjudson said, but with a bit more elaboration.

First, the selector "#panel div" gets all of the divs within the element with an ID of 'panel', which sounds like what you want. Then, using jQuery's 'each' function, you can call an arbitrary function, with each of your divs bound to the 'this' item.

So in the function there, "this" is actually each div's item in the DOM. By referencing $(this) you get the power of jQuery interacting on the item - but if you just need bare properties of the DOM item itself, you can get them straight from 'this'.

$('#panel div').each(function(i) {
    // 'this' is the div, i is an incrementing value starting from 0,
    // per zero-based JS norms
    // If you're going to do a lot of jQuery work with the div,
    // it's better to make the call once and save the results - more efficient
    var $this = $(this);

    // If you want to get out before you're done processing,
    // simply return false and it'll stop the looping, like a break would
    if (i > 4) { return false; }

    // Look up the labels inside of the div
    // Note the second argument to the $ function,
    // it provides a context for the search
    $("label", this).each(function(){
        // 'this' is NOW each label inside of the div, NOT the div
        // but if you created a $this earlier, you can still use it to get the div
        // Alternately, you can also use $(this).parent()
        // to go up from the label to the div
    });
})
Brian Arnold