How do you check if an element exists in jQuery?
<p id="a">A</p>
console.log($('#a').length > 0);
console.log($('#missing').length > 0);
if ($('#missing').length) { console.log('found'); } else { console.log('not found'); }
Console output
true
false
not found
A selector which finds nothing returns an empty jQuery object, and the methods then do nothing. See jQuery Selectors.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |