jQuery - Check if DOM element already exists
This should work for all elements regardless of when they are generated.
if($('some_element').length == 0) {
}
write your code in the ajax callback functions and it should work fine.
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.
Just to confirm that you are selecting the element in the right way. Try this one
if ($('#some_element').length == 0) {
//Add it to the dom
}