Search code examples
javascriptmutation-observers

click is not detecting the presence of the element


Hi,

I need javascript to click an html element but it doesnt appear in the dom right away so I have this code:

document.addEventListener("DOMContentLoaded", function(event) {
  // Select the node that will be observed for mutations
  var parentOfMyList = document.body;

  // Options for the observer (which mutations to observe)
  var config = {
    attributes: true,
    childList: true,
    subtree: true
  };

  // Callback function to execute when mutations are observed
  var callback = function(mutationsList) {
    for (var mutation of mutationsList) {
      if (mutation.type == 'childList') {
        var elt = document.getElementById("topcmm-123flashchat-main-toolbar-message-type-option");
        if (elt) {
            setTimeout(document.getElementById("topcmm-123flashchat-main-toolbar-message-type-option").click, 6000);

          observer.disconnect();
        }
      }
    }
  };

  // Create an observer instance linked to the callback function
  var observer = new MutationObserver(callback);
  observer.observe(parentOfMyList, config);
});

but I get an error that says 'click' called on an object that does not implement interface HTMLElement. Why is that? The element is supposed to be THERE by the time click() is executed (I am even giving it a 6 second head start to catch up).

Thank you.


Solution

  • This has nothing to do with the mutation observer. The element is there, but you're not calling the click() method on it. Since you didn't bind the method to the element, it's being called on window.

    Either pass an anonymous function that calls it on the element:

    setTimeout(function() {
        elt.click();
    }, 6000);
    

    Or you can bind the method to the element:

    setTimeout(elt.click.bind(elt), 6000);