Harshana
Harshana

Reputation: 134

How can i get the child div s and set position with jquery?

<div id="parent">
    <div>a</div>
    <div>b</div>
    <div>c</div>
</div>

I have used fixed positioning. So how can get all the child elements in the parent div with jquery. first child's top:100px and second child's top:200px and so on.

Upvotes: 1

Views: 137

Answers (3)

pythonian29033
pythonian29033

Reputation: 5207

you can use the .children() method to loop through the children;

$("#parent").children().each(function(index){
   var top = (index + 1) * 100;
   $(this).attr("style", "top:" + top + "px");
});

Upvotes: 0

Ram
Ram

Reputation: 144689

You can also use the css method's callback function:

$('#parent > div').css('top', function(i) {
   return ++i * 100 + 'px'; 
});

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

Try this:

 $('#parent div').each(function(index){
   $(this).css({ top: (100*(index+1))+'px' });
  })

Working Fiddle

Upvotes: 1

Related Questions