title: JavaScript function to return only when element exists
body: <p>I am working on a project that requires a dynamic page loading and also requires the function to return once the page has loaded. As it waits on certain parts of the page to load before it can execute anything else.</p>
  
  <p>Currently I am using MutationObservers to detect once the elements appear. Sadly this won't allow to my knowledge for my overall function to return 'true' once the element is found.</p>
  
  <p>I am using this code which after tons of looking is what seems to be what I needed for when I am checking if an element exists. But like I said won't return a value.</p>
  
  <pre><code>//
  //MutationObserver Function : Allows for dynamic page watching without interrupting loading
  (function(win) {
      'use strict';
      var listeners = [],
      doc = win.document,
      MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
      observer;
      function ready(selector, fn) {
          // Store the selector and callback to be monitored
          listeners.push({
              selector: selector,
              fn: fn
          });
          if (!observer) {
              // Watch for changes in the document
              observer = new MutationObserver(check);
              observer.observe(doc.documentElement, {
                  childList: true,
                  subtree: true
              });
          }
          // Check if the element is currently in the DOM
          check();
      }
      function check() {
          // Check the DOM for elements matching a stored selector
          for (var i = 0, len = listeners.length, listener, elements; i &lt; len; i++) {
              listener = listeners[i];
              // Query for elements matching the specified selector
              elements = doc.querySelectorAll(listener.selector);
              for (var j = 0, jLen = elements.length, element; j &lt; jLen; j++) {
                  element = elements[j];
                  // Make sure the callback isn't invoked with the
                  // same element more than once
                  if (!element.ready) {
                      element.ready = true;
                      // Invoke the callback with the element
                      listener.fn.call(element, element);
                  }
              }
          }
      }
      // Expose `ready`
      win.ready = ready;
  })(this);
  </code></pre>
  
  <p>and then I call but obviously this function returns even if company name wasn't filled in. How can I make this function wait until company name was filled in before returning</p>
  
  <pre><code>function fillOutInitial(){
  
  ready("input[id='companyName']", function(element) {
    document.getElementById('companyName').value = "COMPANY NAME";});
  
  
  return "companyName Completed"
  }
  </code></pre>