Hooked
Hooked

Reputation: 88168

Append to an object selected from a list in jQuery

Here is a minimal version of my problem, given:

<div class="foo">
   <div class="a"> </div>
   <div class="b"> </div>
   <div class="c"> </div>
</div>

I want to insert the element <div class="bar">WORKS!</div> into one of the children randomly.

var kids = $(.foo).children();
var idx  = Math.floor(Math.random() * kids.length);
var target = kids[idx];

I think this is a misunderstanding between how javascript and jQuery work together. I'm learning both at the moment, so here is my due diligence in solving the problem:

Upvotes: 0

Views: 29

Answers (2)

Try .eq()

var target = kids.eq(idx);

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try,

var target = kids.eq(idx);

instead of,

var target = kids[idx];

Please read here to know more about .eq()

Upvotes: 2

Related Questions