2

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.

1
  • 2
    It's perfectly fine. In fact I think that's one of the great features of jQuery. Commented Feb 6, 2013 at 17:30

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.