1

I have to set a specific value to an element if the element is exists.

var a = jQuery("#abc");
if(a) {
   a.val("something");
}

For this, I've to check a.length to check the element is exits.

What happen if I directly set the value without checking the element is present or not?

Because, If I do the following

jQuery("#abc").val("dfd");

I don't get any error in chrome when the element is not present. So, can I continue to use like this?

or

any workaround?

Help appreciated!

2
  • 2
    You don't need to check for it. since invoking .val() over an empty jquery object wont harm us. Commented Feb 4, 2015 at 10:36
  • I think everybody is missing the part OP said: For this, I've to check a.length to check the element is exits.. He already know about .length, don't need to suggest it again. Commented Feb 4, 2015 at 10:40

4 Answers 4

2

What happen if I directly set the value without checking the element is present or not?

Nothing. Calling jQuery methods on an empty jQuery object (set) doesn't cause a problem, it just does nothing. This is one of the great things about the set-based concept used in jQuery. The equivalent DOM code (document.getElementById("abc").value = "something";) would throw an error, but the jQuery version doesn't.

Specifically, if the jQuery set is empty:

  • Calling setter methods (like your val call) becomes a no-op.

  • Calling getter methods — for instance, var x = $("#foo").val(); — returns the value undefined.

  • Calling traversal methods — for instance, var divs = $("#foo).find("div"); — gives you a new empty set.

You only need to check (using if (a.length) as you said, or if (a[0])) if you actually care.

jQuery("#abc").val("dfd");

I don't get any error in chrome when the element is not present. So, can I continue to use like this?

Yup.

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

Comments

0

jQuery's val() method simply sets (or gets) the value of each matching element. If there are no matching element, there will be no value to set (or get). You don't need to check if the element exists first.

From jQuery's val() documentation:

Description: Set the value of each element in the set of matched elements.

If there are no matched elements, nothing will happen.

Comments

0

Try with -

jQuery("#abc").length > 0

Comments

0

Yes, you can safely continue. JQuery just executes a function on all elements found by the selector - if there are none, it does nothing. There's no error.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.