views:

41

answers:

3

I have the following example HTML:

<div id="target">
<div id="targetText"></div>
</div>

and I'm using the following code to get the inner div:

$('#targetText');

instead, I was wondering if I could drop the id of the inner element, and somehow match the #target's child?

I have like hundreds of inner children, so, it does not make sense to put an id to each of them. I could just do something like $("#target").innerChild(5); or something. Does anyone know a good way of doing this?

+1  A: 

Like this:

$('#target > :eq(5)')

// or

$('#target').children().eq(5)
nickf
+3  A: 
$("#target > div:eq(0)") //matches the first div child of #target
$("#target > div:eq(4)") //matches the fifth div child of #target
jitter
Works perfectly. Care to explain the syntax? Where is this documented (is this jQuery or ECMAScript)?
rFactor
@Kaitsuli the `>` selects only direct children of the `#target` element, and the `div` limits those children to only select the divs. Finally, it selects the first item (zero-based index) from that result set by using `:eq(0)`.
Doug Neiner
@Kaitsuli: Q#1 Syntax already explained by dcneiner.Q#2 This is jQuery and documented in jQuery documentation in the http://docs.jquery.com/Selectors section
jitter
Depending on the number of children there are, performance-wise, it might be a better to split this to a couple of different function calls (like the second example in my answer). I wrote a blog a little while ago about this: http://spadgos.com/?p=51
nickf
A: 
#target div

unless there are other divs that you don't want to match

#target div:nth-of-type(5)

will match the fifth div that is a child of target. But the selector has limited browser support.

Jason Harwig