0

In my code I'm not checking if a DOM element exists before I manipulate it and jquery does not seem to throw any errors, even if it doesn't exist.

$('.test').addClass('hide');

where the test class doesn't exist, but this doesn't throw any errors.

So is this expected? should I be checking if it exists first?

Tenzin Choklang
  • 504
  • 1
  • 5
  • 21

1 Answers1

0

You can use:

if ($('.test').length) {
   // do stuff
}

With JS only:

document.querySelector('non existing') // => null
Constantin
  • 3,655
  • 1
  • 14
  • 23