Chris Muench
Chris Muench

Reputation: 18318

JQuery empty selector and setting values

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

Answers (2)

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

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

Denys Séguret
Denys Séguret

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

Related Questions