jQuery: How to test or check whether an element exists

by Yang Yang on April 16, 2009

.length property in JavaScript returns the length or number of elements inside an array or the string length. While jQuery selector mechanism $(“elm”) returns an array of DOM objects (such as elements), you can also get the number of the length of the returned objects array by:

$("#some").length

To check the existence of the element, just check if the returned value of length is zero:

if ($("#some").length) { //#some element exists }

Comments on this entry are closed.

Previous post:

Next post: