JavaScript's native innerHTML function is unable to access the content generated by Vue

I have been struggling with extracting the content from a specific div element in my HTML code.

<div id="output" ref="output_data">
   <h1>{{ information }}</h1>
</div>

I attempted to retrieve the contents using innerHTML method as follows:

console.log( document.querySelector('#output').innerHTML );

I also tried accessing it through refs:

console.log( this.$refs['output_data'].innerHTML ); 

However, I was unable to see the content of the #output div. Surprisingly, I could only view the content of information generated by Vue on the webpage.

Below is the entire snippet of code:

<div id="app">
   <div id="output" ref="output_data">
      <span>{{ information }}</span>
      <span>{{ details }}</span>
   </div>
   <button @click="displayInfo">Display Info</button>
   <button @click="displayInfo2">Display Info 2</button>
   <button @click="displayInfo3">Display Info 3</button>
   <button @click="displayInfo4">Display Info 4</button>
</div>

new Vue({
   el: '#app',
   data: {
      information: 'Lorem Ipsum',
      details: ''
   },
   methods: {
      displayInfo: function(){
         this.details = 'sample';
         console.log(document.querySelector('#output').innerHTML);
         // The output contains HTML but 'information' is missing
      }),
      displayInfo2: function(){
         this.name = 'test';
         console.log(this.$refs['output_data'].innerHTML);
         // The output contains HTML but 'information' is missing
      }),
      displayInfo3: function(){
         this.name = 'test2';
         console.log(this.$refs['output_data'].content.innerHTML);
         // Returns an error
      }),
      displayInfo4: function(){
         this.name = 'test3';
         console.log(this.$refs['output_data'].toString());
         // Outputs [object HTMLDivElement]
      }),
   }
});

Answer №1

After some investigation, I discovered that the reason for the issue was Vue not finishing updating the DOM. To resolve this, instead of using the regular method, I implemented $nextTick() and surrounded it with async.

( async function(){
    await _this.$nextTick().then(() => {                      
        console.log(document.getElementById("print").innerHTML);      
    });       
})()

With this adjustment, everything is now functioning properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to create account using PHP

Every time I attempt to create an account, the data I receive is always problematic. The username must be between 3 and 15 characters I find it frustrating that the account creation never goes through successfully. What baffles me even more is that af ...

IE8 triggers automatic download upon receiving JSON response using jQuery

Can you help me make IE8 compatible with this code using jQuery to handle an ajax request that returns data as JSON? $.ajax({ url: formAction, type: 'post', dataType: 'json', data: form, success: ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

SignalR does not include cookies in the connection request

While working on a web application using ASP.NET Web API and SignalR, I encountered an issue that is proving to be quite challenging despite my understanding of HTTP. Currently, I have successfully set a cookie on all AJAX requests to the API, and subsequ ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

Leveraging Iframes for efficient user authentication within an Angular application

Incorporating an Iframe into one of my templates for authentication has presented certain challenges. Case in point: When a user finishes a training session, they must verify their identity by authenticating with a ping identity server that will redirect ...

Utilizing Vue.js with XML data streams

I ran into a problem while working on my personal site with Vue.js. My goal is to display the five latest posts from my Jekyll blog on the page. To achieve this, I am checking the feed at http://todayilearned.dk/feed.xml. However, I'm struggling to ...

Encountering a problem with Vue's v-data-table wrapper component due to identical column value names

Here is my custom v-data-table wrapper component: <template> <v-data-table v-model="selected" :headers="headers" :items="remappedItems" :page="state.currentPage" :items-per-page="s ...

JavaScript Cookie to Ensure Form Submission is Limited to a Single Instance

Seeking assistance with automatically submitting a form on page load using JS cookies. Here is the code I have, but it's not functioning as expected. Any guidance would be greatly appreciated. Thank you. I'm unsure about the section in my code th ...

What is the best way to create a grid item that maximizes the available space in ReactJS Material-UI?

Currently, I am working with the material-ui grid system in a reactjs project. In a column grid container layout, my goal is to display two grid items and have a third item fill up the remaining space between them. Essentially, I want it to look like this: ...

Express server continuously returning 404 error for all requests originating from the index page

Experiencing a challenge with the express/gulpfile.js code. Express can serve the index.html without issue, but it fails to navigate to the lib/* directory resulting in all requests for resources at the top of my index.html returning 404 errors. Browser-s ...

What causes jQuery to not work correctly during keydown events?

I've been working on this external jQuery code: jQuery(document).one('keydown', 'g',function (evt){ if ($("#tb").html() == "0") { $("#tb").html("Testing the chicken.") } else {$("#tb").html("Chickens fart too." ...

What are the best plugins and projects to maximize IntelliJ IDEA's potential for JavaScript development?

I am currently in the process of developing a web application utilizing the MEAN stack: MongoDB, Express, Angular, and Node.js. The foundation of my project is built upon Daftmonk's angular-fullstack Yeoman generator. Despite my primary experience be ...

Vue's push() method is replacing existing data in the array

I'm currently facing an issue where I am transferring data from a child component, Form, to its parent component, App. The data transfer is functioning correctly, however, when attempting to add this data to the existing array within the App component ...

I'm having trouble with my basic routing set up and I'm struggling to understand why it's not working

I'm currently working on a node tutorial and facing some challenges with my routes.js file. Previously, everything was functioning well today as the Node server was able to read the file. However, it seems to be ignoring it now for some unknown reaso ...

What is the best way to dynamically insert components into a grid?

I have structured a grid using the v-for directive. I am looking to insert different components into each column that I've created, one component in each separate column. Although I have set up a script named view where I store the components, I am fa ...

The ng-model binding does not automatically update another ng-model within the same object

Check out this code snippet: http://plnkr.co/edit/aycnNVoD96UMbsC7rFmg?p=preview <div data-ng-app="" data-ng-init="names=['One']"> <input type="text" ng-model="names[0]"> <p>Using ng-repeat to loop:</p> <ul> ...

Generate fake data for all possible combinations using JSON faker

In my current project, I am in need of creating test data for a JSON schema. I came across this fantastic github resource that has been incredibly helpful: https://www.npmjs.com/package/json-schema-faker#overview Now, how can we expand it to generate all ...

Creating a "Container" component in Vue.js step by step

As a newcomer to Vue, I am facing a challenge in implementing a wrapper component similar to React's 'Wrapper' component. Specifically, I want to create a reusable datagrid component using a 3rd-party some-table component and a pagination co ...

Is there a way to instantly remove script from the document head using jQuery instead of waiting a few seconds?

I currently have a setup where I am utilizing Google Maps in production. To make this work, I must include a script in the head of my document that contains the API key for the Google Maps JavaScript API that my application relies on. The API key is being ...