Last Updated: February 25, 2016
·
1.369K
· iondrimba

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
}

2 Responses
Add your response

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 ·