开发者

Checking for a css class on the nearest sibling() div with jQuery?

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!


if ($("#current-div").prev().hasClass("someClass")) {
  // logic here
}


.prev() gives you the previous sibling. You could either do:

if(element.prev().hasClass('featured-item'))

or

if(element.prev('.featured-item').length > 0)


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


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
}


If I got you right, this fiddle should be what you are looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜