Reputation: 18318
If the following selector has a length of 0
$(".my_class")
and I try to do $(".my_class").attr('value', 'test');
It doesn't cause any errors, but should I be checking the length first? What is considered a best practice?
I have a bunch of properties that may or may not exist and am wondering if it is ok to just set an empty jquery value.
Upvotes: 2
Views: 52
Reputation: 66961
You don't need to test for length or anything first because jQuery returns an empty jQuery wrapped object, which is why you are even still able to run the method .attr()
and it doesn't blow up on you!
This is definitely one of the many reasons jQuery is so powerful and easy to use for develoeprs.
Upvotes: 1
Reputation: 382102
No, you shouldn't test the length first, this is as useless as doing
if (n>0) {
for (i=0; i<n; i++) {
In fact, this would precisely be the same thing.
Upvotes: 2