Ali Bassam
Ali Bassam

Reputation: 9969

How to select one of many children inside a DIV

I have this Tree

<div id="chatRooms">
<div class="chatRoom">Lala</div>
<div class="chatRoom">Lolo</div>
<div class="chatRoom">Lili</div>
</div>

$("#chatRooms").children(".chatRoom"); will select all the children, I want to select only 1, regardless of the .html() of these children, this is just an example, how can I do it?

Upvotes: 0

Views: 268

Answers (3)

maddrag0n
maddrag0n

Reputation: 459

if you rely on random selection a lot you could get this jquery plugin which will introduce the :random filter: http://blog.mastykarz.nl/jquery-random-filter/

then you can have something like

$("#chatRooms").children(".chatRoom:random");

OR you could use something like this which does not need another plugin

var count = $("#chatRooms > .chatRoom").length;
var random = Math.Round(Math.random()*count);
$("#chatRooms > .chatRoom").eq(random);

Upvotes: 0

Cranio
Cranio

Reputation: 9847

 $("#chatRooms").children(".chatRoom")[2]; // returns DOM element
                                             not Jquery, must be rewrapped

or

 $("#chatRooms").children(".chatRoom").eq(2); // returns JQuery element

or

 $("#chatRooms > .chatRoom:eq(2)"); // 0-based index!

or

 $("#chatRooms > .chatRoom:nth-child(3)"); // 1-based index! and other differences

for example :)

There are also other options with selectors (as $("#chatRooms .chatRoom:first")) and with Jquery Functions

  $("#chatRooms").children(".chatRoom").last()

Edit: expanded answer also with observations of Ofir Baruch and Esben Skov Pedersen.

Upvotes: 1

defau1t
defau1t

Reputation: 10619

You may use :eq operator, :eq will refer to the index of the element you want to select.

Upvotes: 1

Related Questions