Reputation: 134593
Is there a way in jQuery to return the nearest sibling() div and check for a present class?
I have a visual verticle list of items, in which some items either have a 1px border (to set them apart - premium items) or no border at all (standard items). While it looks great when a premium item is sandwiched between two standard items, when two or three premium items stack up the borders between them end up being 2px thick.
I'm looking for a way, using jQuery or otherwise, to check if the <div class="item">
above the current div has the class featured-item (so checking if the div equals <div class="item featured-item">
). From there, I will set another class name to set border-top to 0px and make the visuals flow a little better.
Can anyone help me out? Sorry if this question is convoluted, hard to explain!
Upvotes: 2
Views: 4477
Reputation: 8265
If I got you right, this fiddle should be what you are looking for.
Upvotes: 1
Reputation: 236092
I'm not really sure you want to check the siblings or the parent nodes. Whatever, if "above" means parent, this will do it:
if( $('div').closest('.item').hasClass('.featured-item') ) { }
For the direct parent you might want to use .parent()
instead of .closest()
If those elements are on the same level and "above" means "before" go with .prev()
if( $('div').prev(.item).hasClass('.featured-items') ) { }
References: .prev(), .closest(), .parent()
Upvotes: 2
Reputation: 13691
if ($("#current-div").prev().hasClass("someClass")) {
// logic here
}
Upvotes: 6
Reputation: 816770
.prev()
gives you the previous sibling. You could either do:
if(element.prev().hasClass('featured-item'))
or
if(element.prev('.featured-item').length > 0)
Upvotes: 2
Reputation: 29831
forward .nextAll([selector])
or back .prevAll([selector])
or both ways .siblings([selector])
.
If the div is truly one sibling before you should be able to do
if($(this).prev('.item.featured-item').length){
// yes it is featured
}
else{
no, not featured
}
Upvotes: 1