title: How to scroll to bottom of div when new elements are added
body: <p>I am trying to make a chat application using Vue and Express.</p>
  
  <p>At the moment, I want to make the container with the messages automatically scroll to the bottom when a new message is sent. I tried to do this by using a <code>scrollToEnd</code> function that selects the div container and assigns its <code>scrollHeight</code> to the <code>scrollTop</code>:</p>
  
  <pre><code>scrollToEnd: function () {
      var messages = this.$el.querySelector('#messages')
      messages.scrollTop = messages.scrollHeight
  }
  </code></pre>
  
  <p>This gives the following error:</p>
  
  <blockquote>
    <p>TypeError: Cannot read property 'scrollHeight' of null</p>
  </blockquote>
  
  <p>For some reason, using the <code>querySelector</code> always returns null, also when I am testing it on other elements.</p>
  
  <p>Below the full code for the component can be found.</p>
  
  <pre><code>&lt;template&gt;
      &lt;div id="messages"&gt;
          &lt;ul&gt;
              &lt;li v-for="msg in messages.slice().reverse()"&gt;{{ msg.message }}&lt;/li&gt;
          &lt;/ul&gt;
      &lt;/div&gt;
  &lt;/template&gt;
  
  &lt;script&gt;
  import MessageService from '@/services/MessageService'
  
  export default {
      name: 'messages',
      data () {
          return {
              messages: []
          }
      },
      mounted () {
          this.getMessages()
  
          this.$root.$on('newMessage', (msg) =&gt; {
              this.message = msg
              this.getMessages()
              this.scrollToEnd()
          })
      },
      methods: {
          async getMessages () {
              const response = await MessageService.fetchMessages()
              this.messages = response.data.messages
          },
          scrollToEnd: function () {
              var messages = this.$el.querySelector('#messages')
              messages.scrollTop = messages.scrollHeight
          }
      }
  }
  &lt;/script&gt;
  </code></pre>