views:

60

answers:

3

I have a big div wit a lot of smaller divs within it. Say,

    <div id="parent">
 <div id="child1">
 </div>
 <div id="child1">
 </div>
 <div id="child2">
 </div>
 <div id="child1">
 </div>
 <div id="child1">
 </div>
</div>

If I'm currently at the last 'child1', how dow I get to the top most child1 with prev()? For me it breaks when it reaches 'child2'.

+4  A: 

First of all your HTML markup is invalid. There shouldn't be more that one element with the same ID in a document.

Read Element identifiers: the id and class attributes

id:

This attribute assigns a name to an element. This name must be unique in a document.

class:

This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.

You can use the parent and :firstchild to get the first element inside your current parent element.

You can use something like this if you are currently at any child of element 'parent'

$(this).parent().find("div:first-child");
rahul
Ok, actually I'm using classes but that was failing so I used IDs. And that's failing too.
mathon12
Thanks. Actually by getting to the topmost 'child1' I meant by traversing the all the previous elements of class 'child1' first. Not directly.
mathon12
+1  A: 
 $(this).closest('.parent').find('.child1:first')

I changed to classes, because you really should only ever have one element of any given ID in a page

David Hedlund
Thanks. That actually solves the problem I described but in div I have there are a LOT of child classes. I'd like to 'skip to the closest previous element of a given class'. Something like $(this).prev('.child1') but I want it to skip the 'child2' class.
mathon12
+2  A: 

I think you want this:

$(this).prevAll('.child1').eq(0);
mtyaka
Hey Thanks!! That's exactly what I seem to be looking for! =)
mathon12