开发者

Iterating through elements of the same class in jquery

开发者 https://www.devze.com 2023-04-08 10:59 出处:网络
I have a collection of div\'s belonging to the same class and having form fields. I want to be able to iterate through the div\'s

I have a collection of div's belonging to the same class and having form fields. I want to be able to iterate through the div's of the same class and get the hidden form elements and store in array.

i have created and array object that adds to an array after each iteration but i think where i am getting it wrong is the iteration through the div's Here is the structure

<div class="parent_div">
    <div class="child_div" id="child_div_1" number="1">
        <div class="some_other_div">
        </div>
        <input id="name_1" type=hidden value="1.0"/>
        <input id="name_2" type=hidden value=开发者_运维问答"4.0"/>
    </div>
    <div class="child_div" id="child_div_2" number="2">
        <div class="some_other_div">
        </div>
        <input id="name_2_1" type=hidden value="1.0"/>
        <input id="name_2_2" type=hidden value="4.0"/>
    </div>
    <div class="child_div" id="child_div_3" number="3">
        <div class="some_other_div">
        </div>
        <input id="name_3_1" type=hidden value="1.0"/>
        <input id="name_3_2" type=hidden value="4.0"/>
    </div>
</div>//end of parent div

I have written the jQuery code below to iterate through these div but I just don't know what I'm doing wrong. So PLEASE HELP!

function doSomething() {
    var array = {};
    var rowCount = $("div .child_div").length;
    var rowNumber = 0;
    for (i=0; i <= rowCount; i++) {
        //doing something...
        array[i] = arrayObj (val1,val2,val3,val4,val5,val6);
    }
}


var values = [];
$(".child_div").each(function() {
    $(this).find("input:hidden").each(function() {
        values.push($(this).val());
    });
});

Also you might get all the inputs and map them:

var values = $('.child_div input:hidden').map(function (index, el) { return $(el).val(); }).get();


You can use the each() method to do the looping.

var $items = $('.myClassName');

var myArray = new Array();


    $items.each(function(){
        var $hiddenItems = $(this).find('input:hidden');
        $hiddenItems.each(function(){myArray.push($(this))});
    });

Working example


$('div .child_div').each(function(i){
   // do something
});


If you just want an array of all hidden inputs that are within div's with the class "child_div", you can do this:

var array = $('.child_div input:hidden').get();

Edit: ... or, if you want to do more complex logic while creating your array, $().map() may be useful. E.g.,

var values = $('.child_div input:hidden').map(function(i, el) {
    // return the value of each hidden input
    return $(this).val();
}).get();
0

精彩评论

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