4

Basically, I want a check to run every time I append or prepend to the DOM that the element I am putting in does not exist. I am making sophisticated applications and on occasion have made duplicate elements causing events to not trigger properly.

I don't want to have to run this check manually each time I change the DOM, I would like it to be ran automatically when the prepend, or append functions are called. Is there an event I could listen for when a function is called?

I wouldn't use this check when the application is released because I realize that it could severely hamper performance, but during development it would be very valuable.

jdw
  • 1,533
  • 3
  • 17
  • 26

1 Answers1

5

Just override jQuery.fn.append:

(function() {
    var append = jQuery.fn.append;
    jQuery.fn.append = function() {
        var elemExists = ...;
        if (!elemExists) {
            append.apply(this, arguments);
        }
    };
})();

Do the same for jQuery.fn.prepend. This works nicely because the only change you have to make for production is to exclude this function.

gilly3
  • 87,962
  • 25
  • 144
  • 176
  • In addition, nowadays you may use the [`Node.contains()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/contains) method. Refs: [How can I check if an element exists in the visible DOM?](https://stackoverflow.com/questions/5629684/how-can-i-check-if-an-element-exists-in-the-visible-dom). – Gras Double Apr 08 '21 at 21:08