Tim Joyce
Tim Joyce

Reputation: 4517

jQuery closest() after siblings return 0

How can I check to make sure the siblings don't contain the class I am looking for before I start traveling up the DOM with closest()? I could do it with the closest() and siblings() functions but I am wondering if there is a jquery function that already exists that would take care of this.

Upvotes: 2

Views: 815

Answers (2)

Blazemonger
Blazemonger

Reputation: 92893

closest() looks up the DOM, siblings() looks to either side; I don't believe there's any jQuery method that does both. You'll have to start with siblings() (possibly with .andSelf()) and then test the length to see if you need to check closest() instead.

Upvotes: 0

Rob W
Rob W

Reputation: 348992

Add the class as a selector to .siblings(). Then, check whether the size of the selection equals zero.

if($(this).siblings('.aRandomClass').length == 0) {
    // No sibling with class aRandomClass
} else {
    // The length is not zero, so there's a sibling with class aRandomClass
}

Upvotes: 1

Related Questions