Obtain a collection of DOM elements using Vue.js

Being a Vue.js user, I encountered an issue while trying to retrieve an array of DOM Elements. Consider the following HTML structure:

<select onchange="toggleDisability(this);" class="mySelect" id="mySelect1">
</select>
<select onchange="toggleDisability(this);" class="mySelect" id="mySelect2">
</select>

In regular JavaScript, fetching all elements with the mySelect class is simple:

var arraySelects = document.getElementsByClassName('mySelect');

However, when attempting the same using Vue's $refs, it seems to only return the last element:

<select id="selection-x" ref="Axis" @change="log($event)"></select>
<select id="selection-y" ref="Axis" @change="log($event)"></select>

This is coupled with the code snippet:

log(selectElement){
   var arraySelects = this.$refs['Axis'];
}

Though emitting the @change event may seem like a solution, it doesn't achieve the desired outcome. The goal is to obtain an array of elements sharing the same ref, similar to how it's done in plain JS where elements with a specific class attribute are selected.

P.S. While aware that ref should be unique, what alternative approach can be taken for this particular scenario?

Answer №1

Unfortunately, it is not feasible with the `ref` and `$refs` in Vue. If you intend to perform DOM manipulation, consider using `vue-directive` or accessing the DOM directly from the root element of the component as shown below:

Vue.extend({
    mounted() {
        // Manipulate the children elements here.
        const children = this.$el.querySelectorAll('.mySelect');
    }
})

Answer №2

One technique that worked well for me was adding a reference to the parent element, as suggested by joaner in a previous comment. Additionally, I found it necessary to execute my code within the "updated" hook in order to ensure that my data had loaded prior to attempting to manipulate the DOM (particularly when using a v-if directive on the same element where child elements need to be accessed):

Here's an example:

<ul v-if="dataLoaded" ref="eventlist">
    <li class="eventItem"></li>
    <li class="eventItem"></li>
    <li class="eventItem"></li>
</ul>

And here is the corresponding JavaScript code:

updated() {
  let eventItems = this.$refs.eventlist.children
  console.log(eventItems)
}

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

The Angular bootstrap datetimepicker doesn't support disabling past dates

Has anyone successfully disabled past dates on an angular bootstrap datetimepicker before? I've tried using the date-disabled attribute, but I can't seem to get it to work. <datetimepicker class="calendar-format" data-ng-model ...

Create a bolded section within a TextField component using Material UI version 5

I am working with a TextField component that has a specific defaultValue set. Here is the code snippet: <TextField autoFocus={props.autoFocus} fullWidth defaultValue={props.defaultValue} value={text} onKeyPress={handleKey ...

Obtain identical socket event in two separate useEffect hooks

I am facing an issue where I want to access the same event in two different useEffect functions on the same page. Despite my attempts, it doesn't seem to work as expected. Below is what I have tried so far. I'm wondering if it's possible to ...

AngularJS: Mastering the art of structuring a single route application

Exploring the best approach to utilize Angular's features for a specific problem I'm working on. The app I am developing will be a single page application with only one route, devoid of any other URL states. It seems like controllers and views c ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...

Angular2 forms: creating validators for fields that are interconnected

Imagine a scenario where a form allows users to input either a city name or its latitude and longitude. The requirement is that the form must validate if the city name field is filled OR if both the latitude and longitude fields are filled, with the added ...

Tips for maintaining user login sessions even after the browser is closed using nuxt auth

I need assistance with the configuration in my nuxt.config.js file: auth: { strategies: { local: { scheme: 'local', token: { property: 'meta.token', global: true, }, user: { property ...

How to Access Data Attribute in React TypeScript on Click Event

Recently, I encountered a situation with my React component where I have a button with a click handler that utilizes the data-* attribute. In the past, with regular React, extracting the value from the data-* attribute was straightforward. However, as I am ...

Tips on incorporating the source path from a JSON file into a Vue component

Is there a way to render images if the path is retrieved from a JSON file? Typically, I use require('../assets/img/item-image.png'). However, I'm uncertain how to handle it in this scenario. Component: <div v-for="(item, index) in i ...

Encountered a runtime error while processing 400 requests

Current Situation: When authenticating the username and password in my Ionic 2 project using WebApi 2 token authentication, a token is returned if the credentials are correct. However, a 400 bad request error is returned if the credentials are incorrect. ...

Is it possible to search a JSON Array using a variable as the criteria

I have a JSON Array that needs to be searched: [ { "Device_ID":"1", "Image":"HTC-One-X.png", "Manufacturer":"HTC", "Model":"One X", "Region":"GSM", "Type":"Phone" }, { "Device_ID":"2", "Image":"Motorol ...

Utilizing jQuery to Select Check Boxes Alongside Labels

In my jQuery code, I have a simple trigger set to run when a radio button is clicked in order to check certain checkboxes on the page. <script> jQuery('#op5').click(function () { $('input[type=checkbox]'). ...

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

Issues with hover functionality in React Material Design Icons have been identified

I'm facing an issue with the mdi-react icons where the hovering behavior is inconsistent. It seems to work sometimes and other times it doesn't. import MagnifyPlusOutline from "mdi-react/MagnifyPlusOutlineIcon"; import MagnifyMinusOutli ...

What is the best way to remove Vuetify and Vue from the build process?

I am developing a custom library using VueCLI and I am looking to optimize the size of the build by excluding vuetify and vue.js from the final bundle. Currently, my final build file (*.umd.min.js) is functioning correctly with the following command: vue ...

Understanding JavaScript's Inheritance

My current Person class looks like this: class Person { constructor(name, age, gender, interests) { Object.assign(this, {name, age, gender, interests}); } } I have also created a sub-class Teacher which inherits properties from the Perso ...

How to access a global jquery function variable inside a foreach loop

Is there a way to modify the value of a global jQuery variable inside a foreach loop each time a new model item is encountered? I am looking to update the calendar with new dates but I need access to certain functions within the foreach loop to achieve thi ...

What is the best approach to retrieve specific data from local storage in order to display it in a JavaScript modal?

Suppose I have the following student records: student[ id : 1, Name: Jake] student[ id : 2, Name: John] Currently, the code snippet below creates a link that opens a modal when clicked, displaying the student's data based on their ID: const link = ...

JavaScript and DOM element removal: Even after the element is removed visually, it still remains in the traversal

Our goal is to enable users to drag and drop items from a source list on the left to a destination list on the right, where they can add or remove items. The changes made to the list on the right are saved automatically. However, we are encountering an iss ...