Retrieve DOM elements within a Vue.js modal using JavaScript

I have integrated the Vue.js modal into my Vue app using a Vue component. The template section of this component includes the modal itself:

<template>
    <!-- Modal: Edit exercise -->
    <modal name='edit-exercise-modal'
           :draggable='true'
           height='auto'>

        <form @submit.prevent='storeEdits'>
            <div ref='myDiv'>Some text</div>
            <!-- Also tried:
            <div id='my-div'>Some text</div>
            -->
        </form>

    </modal>
</template>

I am trying to access DOM elements in order to use the Rangy library and highlight specific text inside my-div. However, every time I attempt to retrieve it using a method, I receive either undefined or null, depending on whether I utilize pure JavaScript or Vue refs:

console.log(this.$refs.myDiv); // undefined
console.log(document.getElementById('my-div'); // null

Upon inspecting with console.log(this.$refs), I can see myDiv under the refs property. Nevertheless, when I pause code execution using debugger immediately after console.log, it appears that refs is empty.

What could be causing this issue? How can I successfully reference the desired div for modification?

Edit: Here's an extended code snippet

<template>
    <!-- Modal: Edit exercise -->
    <modal name='edit-exercise-modal'
           :draggable='true'
           height='auto'>

        <form @submit.prevent='storeEdits'>
            <div ref='myDiv'>Some text</div>
            <!-- Also tried:
            <div id='my-div'>Some text</div>
            -->
        </form>

    </modal>
</template>

<script>

    import Vue from 'vue';

    import VModal from 'vue-js-modal';
    Vue.use(VModal);

    import rangy from 'rangy';
    import 'rangy/lib/rangy-classapplier';

    export default {

        props: [ 'exercise' ],

        /**********************************************
        ********************* Data ********************
        **********************************************/

        data: function() {
            return {
                selected:    [],
                category_id: undefined,
                text:        undefined,
                mistakes:    undefined
            };
        },


        /**********************************************
        ******************** Methods ******************
        **********************************************/

        methods: {
            sampleMethod: function() {
                console.log(this.$refs.textWithMistakes);
                console.log(document.getElementById('text-with-mistakes'));
            }
        },


        /**********************************************
        ******************* Watchers ******************
        **********************************************/

        watch: {
            /**
             * Sets up and shows modal when exercise data is loaded from parent.
             */
            exercise: function() {
                this.category_id = this.exercise.category_id;
                this.text = this.exercise.text;
                this.mistakes = this.exercise.mistakes;

                this.$modal.show('edit-mistakes-exercise-modal');

                // Not working
                this.applyClass(sampleMethod);
                
                // Working, but not a way I'd like to go
                setTimeout(() => {
                    this.applyClass(sampleMethod);;
                }, 3000);
            }
        }
    }
</script>

Answer №1

When the modal is closed, the content inside it is not accessible to you. However, the 'vue-js-modal' component triggers an 'opened' event when the modal becomes visible. Take advantage of this event to execute your code once the modal is open and has finished rendering.

<modal 
  name='edit-exercise-modal'
  @opened="onModalOpened"
  :draggable='true'
  height='auto'
>
   ...
</modal>

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

Guide on building a Vue3 component with TypeScript, Pug Template engine, and Composition API

Whenever I try to export components within <script setup lang="ts"> and then use them in <template lang="pug">, an error is thrown stating that the component is defined but never used. Here's an example: <template la ...

Is it possible to utilize a slot within a Vue.js loop?

I am encountering an issue with a template that is utilizing v-for to loop through. The template includes a named slot where the name is dynamically assigned within the loop. However, no content is displaying as expected. Can someone help me identify wha ...

Cordova Application experiencing freeze on loading Splash Screen

My issue lies in the behavior of the app built with Backbone.js and Cordova. Everything works smoothly when there is an active network connection, but things change when the device goes offline. During each launch under offline conditions, the app exhibits ...

Pressing a button meant to transfer text from a textarea results in the typed content failing to show up

Having trouble with a custom text area called a math field. I'm currently interning on a project to build a math search engine, where users can input plain text and LaTeX equations into a query bar. The issue I'm facing is that sometimes when th ...

To trigger the action of any button in Ionic/Angular, I need to double-click

I am encountering an issue with an app that I developed using the Ionic framework. While the app works perfectly on Android devices, I am facing a peculiar situation on iOS. Every time I click a button in the Simulator or on an actual iOS device, I have t ...

The outcomes of my JavaScript code are not aligning with my expectations

I've been experimenting with printing objects from an API using JSON and AJAX, and I noticed that the console.log works perfectly to display the output. However, I'm having a bit of trouble with my generateCreatureDiv function as it doesn't ...

Sharing the state of a button group across different tabs using Bootstrap 5 and JQuery (or pure JavaScript): A complete guide!

Creating a tabbed web page using Bootstrap 5 nav-tabs for the front end and JQuery for the back end. I aim to have a single radio button group displayed on all tabs, with the state of the group persisting across tab changes. Currently, both tabs display t ...

The Vue component is not displaying any data

Although Axios is successfully loading data, it's not displaying anything. Laravel Mix is also building without any errors. The code I have is as follows: index.html (body) <div id="app"> <posts></posts> </div> In app.j ...

Testing a directive that contains a parent directive declaration is essential in ensuring proper functionality within an

I recently developed a utility tool for my application called batch-checkbox-util.js and I am eager to conduct some tests on it. Although I have written a test script, which can be found at the same link provided, I am encountering an issue during the tes ...

Tips for utilizing Provide/Inject in Vue.js while leveraging TypeScript

I am currently working with Vue.js and TypeScript along with the vue-property-decorator package. The documentation suggests that I can achieve something like this: import { Component, Inject, Provide, Vue } from 'vue-property-decorator' const s ...

Accessing JavaScript results in PHP

Hello everyone! I am working on creating a dropdown menu for selecting time using JavaScript to get the computer's current time. My goal is to have an output that automatically selects the option in the dropdown if it matches the computer's time. ...

A guide on integrating a stacked bar chart from ApexCharts into a modal or v-dialog component

I'm facing a minor issue with vue-apexcharts while attempting to showcase some data in a stacked bar chart. Here is the simple component I have created: <template> <div v-if="this.loaded"> <apexchart w ...

Binding attributes in knockoutjs following an AJAX request

The objective Incorporate the attr binding of KnockoutJS following an AJAX call. The dilemma Check out the code snippet below: $.ajax({ url: "/Products/List?Output=JSON", dataType: "json", success: function (data) { $.each(data, fun ...

javascript if an error occurs, refresh the webpage

Currently, I am inquiring about the most effective method for managing JavaScript errors. Given that my application relies heavily on JavaScript, despite diligent testing efforts, encountering bugs is almost certain. I'm interested in knowing if ther ...

Extract the email address from the HTML source code obtained through a GET AJAX request

An interesting scenario arises when the following code is executed from www.example.com. It fetches the complete html source code of www.example.com/example.html and displays it in an alert message. function process(){ url = "http://www.example.com/ex ...

Understanding the process of parsing an array in form-data in Node.js

https://i.stack.imgur.com/FPhX1.png I'm currently facing an issue while trying to read the image above in Node.js. I am using Express.js and have attempted to debug req.body, but it is returning an empty object {}. Even though I am using app.use(bod ...

Encountering an issue with Next.js React SSR using styled-jsx: unable to access the 'state' property as

I've come across a problem that I can't seem to figure out. Despite my attempts to search for a solution here, I haven't been able to help myself. I'm new to javascript and react, so please bear with me. Issue: I'm using React (1 ...

Interacting with Apexcharts: Exploring a Tiny Column with Hover

While using apexcharts, I encountered an issue with small columns. It can be quite challenging to render the tooltip properly because you have to hover very precisely over the column. Query: Is there a way to expand the hover area to make it easier to int ...

Javascript - Could anyone provide a detailed explanation of the functionality of this code snippet?

Ever since joining a new company 9 months ago, I've been encountering this line of code in JavaScript. It seems to work fine and I've been incorporating it into my coding style to align with the previous developers. However, I'm not entirely ...

Is it possible to dynamically change the color of a box shadow using an event handler?

I'm currently in the process of developing an application that consists of six distinct topics organized within a flexbox structure, complete with a box-shadow effect. My objective is to dynamically alter the color of the box-shadow through an event ...