title: How can I check if an element exists in the visible DOM?
body: <p>How do you test an element for existence without the use of the <code>getElementById</code> method?</p>
  
  <p>I have set up a <a href="http://jsbin.com/apawi5/3" rel="noreferrer">live demo</a> for reference. I will also print the code on here as well:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;script&gt;
      var getRandomID = function (size) {
              var str = "",
                  i = 0,
                  chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
              while (i &lt; size) {
                  str += chars.substr(Math.floor(Math.random() * 62), 1);
                  i++;
              }
              return str;
          },
          isNull = function (element) {
              var randomID = getRandomID(12),
                  savedID = (element.id)? element.id : null;
              element.id = randomID;
              var foundElm = document.getElementById(randomID);
              element.removeAttribute('id');
              if (savedID !== null) {
                  element.id = savedID;
              }
              return (foundElm) ? false : true;
          };
      window.onload = function () {
          var image = document.getElementById("demo");
          console.log('undefined', (typeof image === 'undefined') ? true : false); // false
          console.log('null', (image === null) ? true : false); // false
          console.log('find-by-id', isNull(image)); // false
          image.parentNode.removeChild(image);
          console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should be true?
          console.log('null', (image === null) ? true : false); // false ~ should be true?
          console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this?
      };
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;div id="demo"&gt;&lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Basically the above code demonstrates an element being stored into a variable and then removed from the DOM. Even though the element has been removed from the DOM, the variable retains the element as it was when first declared. In other words, it is not a live reference to the element itself, but rather a replica. As a result, checking the variable's value (the element) for existence will provide an unexpected result.</p>
  
  <p>The <code>isNull</code> function is my attempt to check for an elements existence from a variable, and it works, but I would like to know if there is an easier way to accomplish the same result.</p>
  
  <p>PS: I'm also interested in why JavaScript variables behave like this if anyone knows of some good articles related to the subject.</p>