un7keg
Last Updated: February 25, 2016
·
1.052K
· iondrimba
178548

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
}
Say Thanks
Respond

2 Responses
Add your response

1423
Feb007acc38e70d57f7b4c205f7e8b26

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 ·
1430
178548

That should be another Pro Tip :)

over 1 year ago ·