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

Tips on successfully transferring a JavaScript variable from PHP to JavaScript

I am struggling with how to manipulate a JavaScript variable in my HTML script and then pass it to a PHP file for incrementing by 1. However, I am unsure of how to return this modified variable back to the HTML file for display. Additionally, I am uncertai ...

Tips for implementing xpath in module.exports with mocha javascript

Currently, I am utilizing mocha in conjunction with Node.js and have encountered a challenge. In my scenario, I need to use the XPath defined in one test file (verification.js) and apply it in another file (test.js). The issue arises from the fact that the ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

HighCharts.js - Customizing Label Colors Dynamically

Can the label color change along with gauge color changes? You can view my js fiddle here to see the current setup and the desired requirement: http://jsfiddle.net/e76o9otk/735/ dataLabels: { format: '<div style="margin-top: -15.5px; ...

Import data from JSON using JavaScript

I have a collection of txt files that contain custom content. The file names are stored in a JSON array. { txtFiles: ['./file1.txt', './file2.txt', './file3.txt'] } I am looking to use the require function in JavaScript t ...

After switching from jQuery to pure JavaScript, the code is now up and

After initially coding in jQuery + AJAX, I attempted to rewrite it in vanilla JavaScript. However, the code is not functioning as expected now. Can someone help me identify the mistake causing nothing to display when I run it through the server? I have che ...

Optimize your filtering and searching experience with Vue 3 and Django Rest Framework

I'm a beginner in the world of Vue and Django, trying to create a search component for an e-commerce project that allows users to filter results as they desire. After some research, here's what I've gathered so far: Regarding the front-end ...

Concealing items in a loop using Javascript

I need assistance with this issue. I am trying to hide text by clicking on a link, but it doesn't seem to be working correctly. Even though I tried the following code, I can't figure out why it's not functioning as expected. Is there a diff ...

Is it possible to pass an HTML element's id attribute to a function in JavaScript?

In the following code snippet, I am looking to send the id=content to the function mr and then display the result in the passed id=result. While this functionality is currently limited to this HTML file, I aim to extend it to other HTML pages by adding the ...

Retrieve JSON data within React without the need for importing it

Recently, I've been incorporating data from a JSON file into a React component in a unique way: import data from '../../public/json/data.json'; Using the innovative create-react-app tool, upon running npm run build, the expected behavior o ...

Dynamically Generate Nested Objects in JavaScript

I have an object that is currently empty and I am looking to dynamically create a nested object within it. const obj = {} obj["test1"]["test1.1"] = x //initialize to some variable However, I encountered this error message: Uncaught Typ ...

The AJAX call is failing to update the state data in my React component

I've recently delved into ReactJS and encountered an issue regarding setting state while using an AJAX request. The AJAX call successfully communicates with the server, receiving a 200 code response, indicating that the API request functions properly ...

Discovering the method for keeping track of file changes and executing find-replace operations without registering it as an event within the monitored file

I am confused about why the output displays two lines when typing 'fizbuzz' into the test.txt file. I understand that it is performing a find and replace operation, but how can I avoid it being triggered by the watch function? const watch = requ ...

How can I use Vue.js @scroll to create a dynamic CSS property?

I am developing a vuejs component for my project and I am looking to implement a zoom functionality on scroll within a div, similar to Google Maps. <div @scroll="zoomOnScroll"> <Plotly :data="info" :layout="layout" :display-mode-bar="false"&g ...

Choose a specific parameter from a line using the body parser in Node.js

Upon receiving a post message, I am having trouble selecting a value from CSV data. Here is a sample of what I receive: { reader_name: '"xx-xx-xx-xx-xx-xx"', mac_address: '"name"', line_ending: '\n', field_delim: & ...

Troubles arise when attempting to utilize yarn for my projects

Whenever I enter the command yarn start in the terminal, I get this output: yarn run v1.22.4 $ react-scripts start 'react-scripts' is not recognized as an internal or external command, operable program or batch file. error Command fai ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...

Firefox 3 fails to utilize cache when an ajax request is made while the page is loading

Upon loading the page DOM, I utilize jQuery to fetch JSON data via ajax like so: $(document).ready(function(){ getData(); }); ...where the function getData() executes a basic jQuery ajax call similar to this: function getData(){ $.ajax({cache: t ...

The file reading code in my Node.js application suddenly stopped working

I have a basic web application that I am currently developing using Node.js and Express. This is a breakdown of my package structure: https://i.stack.imgur.com/D7hJx.png The entries in my questions.json file are outlined below: [ { "question": "Wh ...

The functionality of toLowerCase localeCompare is restricted in NuxtJs VueJs Framework

Encountered a peculiar issue in NuxtJs (VueJs Framework). I previously had code that successfully displayed my stores in alphabetical order with a search filter. When I tried to replicate the same functionality for categories, everything seemed to be work ...