I am trying to add some form elements dynamically via Ajax with jQuery. I want to make sure that I don\'t create the same element twice, so I only want to add it if it hasn\
This question is about whether an element exists and all answers check if it doesn't exist :) Minor difference but worth mentioning.
Based on jQuery documentation the recommended way to check for existence is
if ($( "#myDiv" ).length) {
// element exists
}
If you prefer to check for missing element you could use either:
if (!$( "#myDiv" ).length) {
// element doesn't exist
}
or
if (0 === $( "#myDiv" ).length) {
// element doesn't exist
}
Note please that in the second option I've used === which is slightly faster than == and put the 0 on the left as a Yoda condition.