Discover the collection of classes in a DOM element using Vue 3's composition API

I'm currently working on checking if a class exists in a DOM element within my component, but I'm facing some difficulties while trying to achieve this using the onMounted hook:

Below is a simplified version of my template structure:

<template>
        <a
          ref="tabLink"
          href="#"
          role="tab"
          :class="{ chatUpdated: this.chatSessionId === tab.chatSessionId }"
        >
          {{ tab.title }}
        </a>
</template>

This is how my setup function looks like:

  setup() {
    const tabLink = ref(null);
    onMounted(() => {
      console.log(tabLink.value["0"].classList[0]);
    });
  } 

Despite expecting to see the classes of my <a> tag logged out in the console, I keep getting an undefined value. It's puzzling because I assume that the component's DOM should have been loaded by the time the onMounted hook is triggered, so it's unclear why the value is coming out as undefined.

Answer №1

Your approach in finding the class is incorrect.

Here's what you should do:

const tabLink = ref(); // make sure to remove the null value here

console.log(tabLink.value.className); // retrieves all classes as a string
console.log(tabLink.value.className.split(" ")); // converts classes into an array

Answer №2

According to the Vue documentation:

When making changes to reactive state in Vue, the updates to the DOM are not applied immediately. Instead, Vue stores them until the "next tick" to ensure that each component is updated only once regardless of how many state changes were made.

In this scenario, there is a class binding on the <a> element that depends on the value of chatSessionId. The effect of this binding will be visible in the next tick.

Solution

To observe the effect, await a call to nextTick():

            👇
onMounted(async () => {
    👇
  await nextTick()

  // now you can see the effect of the class list
  console.log(tabLink.value[0].classList[0])
})

Check out the demo

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

Disabling a button based on the result of a database query

Is there a way to dynamically enable or disable a button based on the result of a database query in JavaScript? I have managed to display an error message (with id="error") depending on the result, but toggling the button (with id="generate") doesn't ...

Error encountered while attempting to send a delete request to MongoDB due to connection refusal

Recently, I've been diving into a Next.js tutorial that involves working with MongoDB. Everything seems to be running smoothly when testing my API endpoints with Postman. POST, GET, and DELETE requests all go through without any hiccups. However, thi ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

aiplafrom struggles to establish a customer using Vite alongside Vue and TypeScript

I'm currently experimenting with Gemini Pro on Vite + Vue + TS, but I encountered an issue when attempting to create an instance of PredictionServiceClient. The error message displayed is Uncaught TypeError: Class extends value undefined is not a cons ...

Steps to configure a proxy in Nuxt3

I can't figure out why my proxy settings in nuxt 3 are not working properly. When I try to fetch data, I notice the URL is incorrect in the development tools. https://i.sstatic.net/fSCuJT6t.png Here is my code. What am I doing wrong? nuxt.config.js e ...

Top tip: Utilize jQuery for the most effective method of adding content to the HTML of a paragraph situated

One interesting challenge I'm facing involves a textarea that stores dynamic HTML content within paragraph (p) tags. Initial HTML: <textarea rows='7' class='form-control' id='comments'><p>My variable HTM ...

Error: The object #<HTMLCollection> does not support the 'tags' method

While trying to troubleshoot this issue, it seems like I haven't been able to pinpoint the simple solution. This particular javascript menu works perfectly in IE, however in Chrome, there is an error when trying to open the menu with a first-level cli ...

The Evolution of Alternatives to contentEditable

Related: ContentEditable Alternative I am curious about the timeline of online WYSIWYG editors prior to the existence of contentEditable. I remember using GDocs and GMail with rich-text features that functioned similarly to contentEditable. I would appre ...

Issues with jKit Pagination (Controlling Size by Height)

I'm currently utilizing the jkit paginate feature to limit the number of items by height, with the setting at 910 pixels. Everything works fine when there is enough content to exceed this limit and create a second page. However, if the content falls ...

Retrieving a portion of a file using Jquery ajax

I am struggling with extracting specific content from loaded data using the following simple sample code: $.ajax({ url: 'demo2.htm', success: function(loadeddata){ $("#loaded_data").after(loadeddata); alert('success'); }, ...

Is it possible for a single field to validate and accept multiple types of data?

As a newcomer to Yup, I am attempting to validate a field that can be either a string following a specific regular expression or an array of such strings. Below is a functional example of validating a string that matches the regex: { field: yup.string(). ...

Receiving array data in a Javascript function and storing it within a variable

Hello everyone, please take a look at my code below. I am attempting to pass PHP array values to a JavaScript function. When I run the script, I receive alerts for parameter0=1, parameter1=2, and parameter2=3 separately. What I am trying to achieve is to ...

Accessing a form by inputting a personal identification number

I am in the process of developing a web application form that requires users to make a payment before gaining access. After completing payment and receiving the PIN number, users must enter the number correctly to be granted access. If incorrect, access w ...

Is there a way for me to link my script for use in a Detail.cshtml file?

I have added the following script to my _Layout.cshtml shared master view: <script src="@Url.Script("~/Scripts/PromptToSave.js")" type="text/javascript"></script> Is there a way to include this script in a Details or index page that does not ...

Dynamically loading form element values

Is it feasible to retrieve dynamic values within a form using jQuery? Consider this example: <form id="contact" method="post" action"contact.php" class="ajaxForm"> <label>Name:</label> <input type="text" name="name" /> ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

bespoke theme background hue

I currently have material-ui@next installed and I am attempting to customize the background color of the theme. Here is what I have tried: const customizedTheme = createMuiTheme({ palette: createPalette({ type: 'light', primary: purple ...

Getting Creative with Jquery Custombox: Embracing the 404

Encountering a problem with jquery custombox version 1.13 <script src="scripts/jquery.custombox.js"></script> <script> $(function () { $('#show').on('click', function ( e ) { $.fn.custombox( this, { ...

What is the functionality of the nested activation in Vuetify components?

Exploring a nested activation scenario, we encounter the following: v-on="{ ...tooltip, ...menu }"> instead of v-on="{ tooltip, menu }"> For example: <template> <v-tooltip> <template v-slot:activator="{on : tooltip}"> ...