title: How to wait for DOM to load after click event in javascript?
body: <p>I'm writing a script to scrape data. The page has a list where each item can only be expanded one at a time, where &quot;expanding&quot; means rendering a <code>div</code> under the selected row with some data that is fetched on click. The script looks something like this:</p>
  <pre class="lang-js prettyprint-override"><code>function findData(arr, matches_regex) {
    return Array.prototype.slice
      .call(arr)
      .find((x) =&gt; matches_regex(x.textContent))?.textContent;
  }
  
  rows = document.getElementsByClassName(&quot;selectable-row&quot;)
  data = []
  for (var i = 0; i &lt; rows.length; i++) {
    rows[i].click()
    row_data = document.getElementsByClassName(&quot;row-data&quot;)
    data1 = findData(row_data, matches_regex_1)
    data2 = findData(row_data, matches_regex_2)
  
    data.push([data1, data2])
  }
  </code></pre>
  <p>The problem is, after <code>rows[i].click()</code> the rest of the script runs before the DOM loads the fetched data, and so data1 and data2 are &quot;undefined&quot; where there should be data. Is there a way to wait for the DOM to fully load after the click before getting the data?</p>