开发者

jQuery addClass to every item that have x children?

开发者 https://www.devze.com 2023-04-10 14:24 出处:网络
I want to add class \"anything\" to every item that has more than 2 children. Unfortunately my code doesn\'t work, I guess I have to define (this) and maybe use each, but I\'m not sure how to do that.

I want to add class "anything" to every item that has more than 2 children. Unfortunately my code doesn't work, I guess I have to define (this) and maybe use each, but I'm not sure how to do that.

Here's my code:

if ( jQuery('#container .document').children().size() > 2 ) {
     jQuery(this).addClass("anything"); 
}

An 开发者_运维知识库broken example:

http://jsfiddle.net/HHSuM/1/


You can use filter to restrict the list to elements with more than two children.

jQuery('#container .document').filter(function() {
    return this.children.length > 2; //Use just the regular DOM children property in here
}).addClass("anything");

JSFiddle: http://jsfiddle.net/HHSuM/4/


Loop over the elements with .each():

$('#container .document').each(function() {
  if (this.children.length > 2) {
    $(this).addClass('anything');
  }
});


I thought this was an interesting one, and tried to use :has() in conjunction with :nth-child() but I get a syntax error.

// Does NOT work... why?
jQuery('#container .document:has(*:nth-child(3))').addClass('anything');

But modifying the approach slightly, works:

// Nifty!
jQuery('#container .document *:nth-child(3)').parents('.document').addClass('anything');

Basically we're looking for elements with a 3rd element, then moving up the DOM.


Use .each() to iterate through the #container .document elements.

Updated your jsfiddle. Seems to work!


you have many options here

  1. you can use .each() to iterate over the items, check in the callback function whether they have 2 children or more and then add the class

  2. another option i like better, is using the .filter() like this:

    $('#container .document').filter(function(){  
        return $(this).children().length > 2;
    }).addClass('anything');
    

    or your example: http://jsfiddle.net/saelfaer/HHSuM/6/

0

精彩评论

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

关注公众号