Hide Element after div is loaded dynamically

There is a normal procedure in javascript to hide any element based on page load or click event. For eg, when the page is loaded and DOM is built, using the below code snippet, a button is able to hide the element after it is clicked.

$.function($) {
  $("#button").click(function() {
    $('#div').hide();
  });
}

Similarly, an element can be hidden based on some condition when the page is loaded. Eg - consider the below snippet -

$.function($) {
  if ($('#div').length()) {
    $('#textbox').hide();
  }
}

The above code hides the textbox element if the div element is present on the page.

Now, what if the div appears dynamically on the page after some event, i.e, a page is loaded and then a checkbox is used to load the div section using ajax. We might need to check the MutationObserver in this case. This interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification.

$(function($) {
  //initialise the config that need to be listened.
  var eventTypes = {childList: true};

  var mutationObserver = new MutationObserver(function(mutationRecords) {
    $.each(mutationRecords, function(index, mutationRecord) {
      if (mutationRecord.type === 'childList') {
        //Hide the textbox if any node is added inside the element.
        if (mutationRecord.addedNodes.length > 0) {
          $('#textbox').hide();
        }
      }
    });
  });

  var targetNode = $("#parentDivElement");
  //Start observing the target node.
  mutationObserver.observe(targetNode, eventTypes);

  // Later, you can stop observing
  observer.disconnect();
});

The eventTypes variable is used to check if any child is added under the parentDivElement. As the event type childList is triggered, the mutationRecord checks for the nodes under the main div and hides the textbox if any element is added as a child.