简体   繁体   中英

How do I check an element is exists in JQuery?

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!

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.

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.

尝试-

jQuery("#abc").length > 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM