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't already been added to the DOM.
All of my elements have a unique CSS id, for example:
$('#data_1')
I am using the following to check if the element already exists:
if ($('some_element').length == 0) { //Add it to the dom }
However, it only works for elements which were already part of the page when it first loaded.
How do I also check for elements which were dynamically created after the page was loaded?
Any advice is appreciated.
Thanks.
The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. Syntax: $(selector). hasClass(className);
Answer: Use the jQuery . length Propertylength property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists in DOM.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With