Home > OS >  Can we add optional chaining in .classlist for null checking in jquery?
Can we add optional chaining in .classlist for null checking in jquery?

Time:07-06

can we use optional chaining, i.e "?." for null checking ...

$(.class)?.get(0)?.classList.add('hidden);

because am, getting errors like "Cannot read properties of undefined( reading 'classList') when .class is not availble

CodePudding user response:

The best way to use is to use like this:

$('.class').get(0).addClass('hidden')

CodePudding user response:

first of all there no need to check if .class exists, but just for the sake of code you can try this:

 if($(".class").length >0){
  $(this).addClass("hidden");
  }
  • Related