Verify if jQuery found an element
If you want to check if jQuery found an element, always check for its length
var element = $(selector);
if (element.length) {
//do something
}
Written by Ion D. Filho
Related protips
2 Responses
It may be a good idea to assign the jQuery object to a var, especially if your selector works on a large DOM.
Concider:
var $testDivs = $("#test").find("div");
if ($testDivs.length) {
//use $testDivs without searching the DOM again
}
over 1 year ago
·
That should be another Pro Tip :)
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#