title: Accessing DOM elements with querySelector, getElementById or getElementByClassName during processing of content with asynchronous js functions
body: <p>This could be the problem of many people, especially beginners or such people who don't code Javascript very often. It is a very mean issue because this kind of an issue does NOT throw any errors. So it will be hard to identify.</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>async function getJSONFile(pathtofile) {
    var request = await fetch(pathtofile, {
      method: "GET"
    });
    var response = await request.text();
    var data = await JSON.parse(response);
    return data;
  }
  
  async function number1() {
    var url = "https://support.oneskyapp.com/hc/en-us/article_attachments/202761627/example_1.json";
    var data = await getJSONFile(url);
    var newElement = document.createElement("div");
    newElement.innerHTML = "My favorite company is " + data["fruit"] + "!";
    newElement.classList.add("child");
    document.querySelector("div#parent").appendChild(newElement);
    newElement = null;
    newElement = document.createElement("div");
    newElement.innerHTML = "Here's the full content of the json file: " + JSON.stringify(data);
    newElement.classList.add("child");
    document.querySelector("div#parent").appendChild(newElement);
    console.log("Function number1 was executed");
  }
  
  number1();
  
  function number2() {
    var childOfMainDiv = document.querySelectorAll("div#parent &gt;  div.child");
    console.log("Function number2 was executed");
    console.log(childOfMainDiv);
  }
  
  number2();
  
  /* Even though function number1() is called first and it is the first function being executed, BUT(!) it also continues with function number2() which finishes before function number1() that is still processing and fetching the JSON file. 
  
  As a result our querySelectorAll method will not have access to any child DOM (HTML) elements during the execution time of  function number1(). 
  
  This is because the child elements are going to be appended BY finishing the execution of function number1().
  
  I really hope that this example would be helpful and easily understandable for others who experience such problems. */</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="parent"&gt;Parent div container&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>