title: querySelectorAll not working
body: <p>I have a requirement where I have to pickup the last <code>.div</code> within a container and apply some business logic to it. The selection of the last <code>.div</code> has to be dynamic because the user has the option to add/remove <code>.div</code> elements.</p>
  
  <p>Initially I tried with <code>querySelectorAll</code> but it did not seem to work. So I decided to change it to <code>getElementsByClassName</code> and surprisingly it worked with the same logic. Can somebody please help me with the reason for why the <code>remove_div</code> doesn't work while the second one (<code>remove_div_2</code>) does?</p>
  
  <p>Note: I am not looking for a fix/solution to the issue because I have already proceeded with the second option. I just want to know the reason why the option with <code>querySelectorAll</code> doesn't work.</p>
  
  <p>Below is my code:</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;div id='container'&gt;
      &lt;div id='div1' class='div'&gt;This is Div 1&lt;/div&gt;
      &lt;div id='div2' class='div'&gt;This is Div 2&lt;/div&gt;
      &lt;div id='div3' class='div'&gt;This is Div 3&lt;/div&gt;
  &lt;/div&gt;
  &lt;button type='button' id='append_div'&gt;Append Div&lt;/button&gt;
  &lt;button type='button' id='remove_div'&gt;Remove Div&lt;/button&gt;
  &lt;button type='button' id='remove_div_2'&gt;Remove Div 2&lt;/button&gt;
  </code></pre>
  
  <p>JavaScript:</p>
  
  <pre><code>window.onload = function () {
      var elementToStyle = document.querySelectorAll("#container .div");
      elementToStyle[elementToStyle.length - 1].classList.add('red');
  
      document.getElementById('append_div').onclick = function () {
         var divToInsert = document.createElement('div');
         divToInsert.id = 'new_div';
         divToInsert.className = 'div';
         divToInsert.innerHTML = 'This is an appended div';
         document.getElementById('container').appendChild(divToInsert);
         var elToStyle = document.querySelectorAll("#container .div");
         for (i = 0; i &lt; elToStyle.length; i++)
             elToStyle[i].classList.remove('red');
             elToStyle[elToStyle.length - 1].classList.add('red');
         };
  
         document.getElementById('remove_div').onclick = function () {
             var elToStyle = document.querySelectorAll("#container .div");
             document.getElementById('container').removeChild(elToStyle[elToStyle.length - 1]);
             elToStyle[elToStyle.length - 1].classList.add('red');
         };
  
         document.getElementById('remove_div_2').onclick = function () {
             var elToStyle = document.getElementsByClassName('div');
             document.getElementById('container').removeChild(elToStyle[elToStyle.length - 1]);
             elToStyle[elToStyle.length - 1].classList.add('red');
         };
     }
  </code></pre>