Home > Back-end >  using "this" in each function , how to use with different class
using "this" in each function , how to use with different class

Time:12-04

example below , i want to do something different if some of the #div has a unique class. I get error using hasClass and find

$('.div').each(function(){
    if($(this).find('span').length === 2){
        // this works
        }
    if($(this).hasClass('test').find('span').length === 1){
        // this doesnt work - error hasClass and find not a function - so how can i use this , but for a "this" with unique class ?
    }
});

This works fine on its own , but why cant i define in same function

$('.div .test').each(function(){
    if($(this).find('span').length === 1){
        // this works
    }
});

This does not work

$('.div').each(function(){
    if($(this).find('span').length === 2 || $(this).hasClass('test').find('span').length === 1 ){
        // error hasClass and find not a function
        }
    }
});

CodePudding user response:

The issue is because hasClass() returns a boolean, not a jQuery object, so you can't chain another jQuery method from that.

You can work around this by using filter() instead:

if ($(this).filter('.test').find('span').length === 1) {
  // do something...
}

CodePudding user response:

Use this condition instead:

If ( $(this).hasClass('test') && $(this).find('span').length === 1) {

  • Related