How to check if an html element exists in Jquery?

Dung Do Tien Apr 22 2020 561

In my form, have used html()  to append more HTML tags into a div.  How can I check element I just append whether there exists or not.

$(".container").html('<div id="divId"></div>');

And check to exist I check as below but it is not working.

if($("#divId").html().length > 0){
   // div exists and do something here.
}

Thank you for any suggestions.

Have 1 answer(s) found.
  • S

    Sandeep Kumar Apr 22 2020

    In Jquery, you can use .length property to check number of elements or length value of an element. This property will return the number match with your rule defined.

     

    In your code, you are checking value length of div. It is not check element exists. To check element exist you can do as below :

    if($("#divId").length > 0){
       // div exists and do something here.
    } 

    and if you using Javascript:

    var lengthExist = document.getElementById("divId");
    if(lengthExist != null){
       // To do something here
    } 

    I hope it resolves the problem for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close