28

Possible Duplicate:
Is there an “exists” function for jQuery

Say for instance you have the div:

<div id="hello"></div>

And you are dynamically creating a div:

<div id="hello"></div>

Is there a function you can use in Jquery which will check to see if the object with the ID you are trying to create already exists on the page?

0

2 Answers 2

17

For jQuery method you could go with

if($("#selector").length) {
    //object already exists
}
1
  • simple, great. this works perfectly
    – TaylorMac
    Commented May 20, 2011 at 4:21
15
if (document.getElementById('hello')) {
    // yup, already there
}

Or, the jQuery way:

if ($('#hello').length) {
    // yup, already there
}
3
  • Even shorter: ($('#hello')[0]) Commented May 19, 2011 at 1:44
  • If you are creating multiple elements before you add them to the page, you can give them the same id with this check. An element can have an id but will not be found with document.getElementById until it is part of the document.
    – kennebec
    Commented May 19, 2011 at 3:13
  • +1 nice to see both option mentioned here
    – jim tollan
    Commented Jun 12, 2014 at 12:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.