In JQuery to check that element is exists or not we use length() function. Using length() function we will check the length of the selector, if it returns something then the element must exists else not.
if( $('#selector').length ) // to check the id selector
{
// exists
}
if( $('.selector').length ) // to check the class selector
{
// exists
}
For example,
<h1 id="heading">This is a Heading</h1>
<p>This is a paragraph.</p>
Suppose we have to check the element with id heading exists or not. For this, we will use the following code:
if( $('#heading').length ) {
alert("exist");
}else
{
alert("does not exist");
}
0 Comment(s)