getElementById inside the vue js mounted life cycle hooks results in null

Viewed 1824

I've been getting null when I try to see what's inside an id with document.getElementById. Part of the code is below:

<input-layout v-if="edit" label="Status" class="grayout">
        <u-select v-model='test.status' :options="testStatus" tabindex="14" class="grayout" id="testStatusDropDown"/>
</input-layout>

<input id="input1" type="checkbox">

Note that, v-if="edit" results in true.

In the mounted life cycle hook I have:

mounted () {
      this.$nextTick(function (){
      console.log(document.getElementById("input1"))
      console.log(document.getElementById("testStatusDropDown"))
    })
  },

Originally I didn't have the console.log statements in the mounted method which resulted in null for both input1 and testStatusDropDown. I understand that because both elements do not exist yet when that part of the code runs. So then I moved them into the mounted method, now, I can see <input id="input1" type="checkbox"> but for the second log statement I get null.

I went to the vue js mounted api docs, which can be found here: https://v2.vuejs.org/v2/api/#mounted. From what I can see is that mounted does not guarantee all child components have been mounted so I need to use this.$nextTic inside the mounted method. However, even after adding this.$nextTick I'm still having the same issue where document.getElementById("testStatusDropDown") results in null when I expect it to be <u-select v-model='test.status' :options="testStatus" tabindex="14" class="grayout" id="testStatusDropDown"/>.

Is my expectation incorrect? What do I need to change such that document.getElementById("testStatusDropDown") does not return null?

1 Answers

Use ref to reference an element in vuejs.

<input id="input1" ref="input1" type="checkbox">

and in mounted access it using:

this.$refs.input1
Related