How to access DOM in Vue.js

786 Views Asked by At

I am trying to access the DOM using Vue.js. I am writing the code inside the mounted() lifecycle, however I am not getting any results.

The code works perfectly fine using vanilla JavaScript.

I am using the v-html directive to insert html inside the span tag.

    <span class="email" v-html="text"></span>

Then in mounted lifecycle

  mounted() {
    let images = document.getElementsByClassName(
      "mcnImageCardBottomImageContent"
    );
    console.log(images);
    // It is returning an empty array
 
  },

How to access the DOM in Vue.js?

2

There are 2 best solutions below

0
On

You need to know that the HTML markup what you see in Vue.js or react isnt really a HTML markup. It gets parsed down to pure javascript object, to an virtual DOM.

You need to wait till vuejs renders its virtual DOM. You can do it with this.$nextTick()

mounted() {
   this.$nextTick(() => {
      let images = document.getElementsByClassName(
        "mcnImageCardBottomImageContent"
      );
      console.log(images);
        // It is returning an empty array
      })
}
1
On

Would something like this work? :)

  mounted() {
    document.onreadystatechange = () => {
      if (document.readyState === "complete") {
        console.log("Page loaded");
        // Do stuff here
      }
    };
  }