8

I want to check whether an element exists in the whole page or not. Is there any way to know if the element exists in the page through jQuery?

For example:

<html>
     <body>
        <p id="para1" class="para_class"></p>
     </body>
</html>

In the above code, I have to check whether <p> of id para1 exists in the DOM or not. In any case if with the help of the 'class' attribute we can know if the element exists, it also would be helpful.

3 Answers 3

13

For element IDs:

if($('#para1').length){
  //element with id exists
}

For element class:

if($('.para_class').length){
  //element with class exists
}
Sign up to request clarification or add additional context in comments.

Comments

0

recently I faced the same problem & this is good for me.

if ( $('#para1').length == 1 ){ // if the id exists its length will be 1 

      alert('This Id exists');

} elseif ( $('#para1').length == 0 ){ // if the id doesn't exists its length will be 0

      alert('This Id does not exists');
}

Comments

0

I know I'm a little late, but, to check if an input doesn't exist with an id using JQuery, you can do this:

if (!$('#inputid').length > 0)) {
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.