mathon12
mathon12

Reputation: 181

Closest previous element with certain ID (with prev())?

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'.

Upvotes: 2

Views: 1287

Answers (3)

mtyaka
mtyaka

Reputation: 8848

I think you want this:

$(this).prevAll('.child1').eq(0);

Upvotes: 4

rahul
rahul

Reputation: 187030

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");

Upvotes: 7

David Hedlund
David Hedlund

Reputation: 129792

 $(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

Upvotes: 1

Related Questions