23

Heres my element, i want to arrange the children inside it by looping through them.

<div id="animDummy1">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

Heres how i imagine the code should look but children(), of course, doesn't return an array of the children

var children=$('#animDummy1').children();
for(var i=0;i<children.length;i++){
    children[i].css('left',i*120+'px');
}

The question - can i get children array for use in a loop? I know i can attach a function for each of children to be executed on, but can i get that increasing "i" in there?

Thnx.

Martin
  • 1,752
  • 2
  • 13
  • 21

9 Answers9

34

children() returns a jQuery object of the children which resembles an array of DOM nodes. Your problem is inside the loop - when you access individual objects with [] you get back plain DOM nodes which don't have a css method. Either use .eq(i) or $(children[i]).

Or just use the each() method, which lets you do the same without having to write a for loop by hand. Read the docs to find out how to get the index of the element inside the callback.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • 3
    This isn't really correct - `children()` returns a jQuery object not an array. It does have "indexes" that can be used by jQuery.each(), but it's not of type array. Try using `children().toArray()` if you'd like to get an actual array. To confirm this, try out `children() instance of Array` vs `children().toArray() instanceof Array` :) – Jason Oct 10 '14 at 17:52
  • @Jason: Fine, I guess my language wasn't 100% exact. – Matti Virkkunen Oct 10 '14 at 18:30
13

This is the correct way.

var children=$('#animDummy1').children();

children.each(function(idx, val){
   $(this).css('left',idx*120+'px');
});

or actually this is better.

$('#animDummy1').children().each(function(idx, val){
   $(this).css('left',idx*120+'px');
})
thenetimp
  • 9,487
  • 5
  • 29
  • 42
8

The other answers to use jQuery's children().each() are likely helpful for most cases. However, if you do need an actual javascript Array, you can do the following:

var childrenArray = $('#animDummy1').children().toArray();

This would allow you have a real array for use in a loop or with other functions that require an array as a parameter.

divykj
  • 576
  • 6
  • 12
Jason
  • 2,691
  • 27
  • 28
4

children() returns a set of jQuery objects and children[i(anyNumber)] will return the dom element. So calling css jQuery method on dom element will through an error. You should use eq method if you want to access any particular element at a given index. Try this.

var children = $('#animDummy1').children();
for(var i = 0;i < children.length;i++){
    children.eq(i).css('left', (i*120+'px') );
}

.eq() reference: http://api.jquery.com/eq/

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
4

Many jQuery methods let you pass a function directly in place of the new value you want assigned.

For your example...

$('#animDummy1').children().css('left', function(i, curr_left) {
    return i * 120;
});

So here I called .css() directly on the .children() set, and instead of a number for the 'left' value, I gave a function.

The function is invoked once for each element. The parameters represent the index of the current iteration, and the current css value of the current element in the iteration.

The return value of the function will be used as the value to set on the current element.

2

Use jQuery:

.each() get allow to each index of array with childrens of $('#someObject'):

$('#animDummy1').each(function(index, item) {
   // Do Something with each $(item) children of #animDummy with index
});
Ivan Trubnikov
  • 177
  • 1
  • 8
2

This works fine for me

$(document).ready(function(){

    var children = $('#animDummy1').children();        

    $(children).each(function(index, item){                 
        console.log(index);            
    });           
});

jsFiddle Example

Gabe
  • 49,577
  • 28
  • 142
  • 181
1

Little touch and code is working.

var children=$('#animDummy1').children().toArray();

var children=$('#animDummy1').children();
for(var i=0;i<children.length;i++){
    $(children[i]).css('left',i*120+'px');
}

Your code is ok except $(children[i]) and define children as array with .toArray()

Nuri YILMAZ
  • 4,291
  • 5
  • 37
  • 43
0
    $(function () {
        var sortOrder = [3, 4, 1, 5,2];
        var onLoad = $('#parentDiv>p').get();
        for (var i = 0; i < onLoad.length; i++) {
            var inRearranging = $('#parentDiv>P').get();
            var orderingID = "#paragraph" + sortOrder[i];
            $(orderingID).insertBefore("#" + inRearranging[i].id);
        }
    });



<div id="parentDiv">
    <p id="paragraph1">1</p>
    <p id="paragraph2">2</p>
    <p id="paragraph3">3</p>
    <p id="paragraph4">4</p>
    <p id="paragraph5">5</p>
</div>