It happens that in my page I am adding several elements to the DOM dynamically, using the one .append()
from jquery , but in a div I have an element that I would like to know first if it exists or not, since if I give it an .append()
element again it would be added again.
It occurred to me to always do a .remove()
before .append()
to remove any instances of the object that were previously added. If it works for me, but I imagine there are other better ways to do it?
If jQuery is necessary, you can use:
Another solution with javascript , taken from the Mozilla Developer Network :
Where node is the element you want to confirm whether or not it exists.
Probably the easiest way is...
either
In a project where I create a lightbox with vanillajs (without using jquery) I had to close the div that I had created, but it gave me an error because the node I was looking for did not exist, I came to this post and it served as a guide to validate without errors if My element existed or not, but not with the scripts they proposed. I came to this solution (in my case):
ES2015 version
es5 version
Jquery version
A dynamically created tr and added to a table in any node I can find out if it exists using contains(trD) and if I want to delete it without error I do it like this: