Steven Zack
Steven Zack

Reputation: 5104

jQuery: how to know the div already exists?

I'm developing a web application, need to append some text to a specific div(id=div_specific). The div is dynamic generated by program, so I need to verify if the div already exists, otherwise, I have to create that div first. How to verify if the div already exists?

Upvotes: 0

Views: 902

Answers (4)

Brandon
Brandon

Reputation: 2125

if($("#div_specific").length == 1) { /* do stuff */ }

Upvotes: 1

David
David

Reputation: 844

Simply:

  if($("#mydivname").length) {
    // do something cool with the div
  } else {
    // create it
    $("#mydivparent").append("<div id='mydivname'>hello world</div>")
    // now do something cool with the new div
  }

Upvotes: 1

Andrew
Andrew

Reputation: 13853

This should do the trick,

if($('#' + div_specific).length == 1){
  alert("I Exist");
}

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95508

if(jQuery("#id_specific").length > 0) {
   ...
}

else {
   ...
}

Upvotes: 6

Related Questions