Can't get className to work in VueJS function

I need help changing the classNames of elements with the "link" class. When I call a method via a click action, I can successfully get the length of the elements, but adding a class does not seem to work. Does anyone have any insights into this issue?

HTML

<div id="app">
  <ul>
    <li><a href="#" class="link" @click="myFunc">Link text 1</a></li>
    <li><a href="#" class="link" @click="myFunc">Link text 2</a></li>
    <li><a href="#" class="link" @click="myFunc">Link text 3</a></li>
  </ul>
</div>

JS

var app = new Vue({
el: '#app',
methods: {
  myFunc: function(event){

      // works
      var ElLength = document.getElementsByClassName('link').length;
      console.log('ElLength = ' + ElLength);

      // does not work
      document.getElementsByClassName('link').className += " hullaballoo";

    }
  }
});

JSFIDDLE

Answer №1

document.querySelector('.link') 

fetches an array-like object of HTML elements, and .classList is a property of each element in this collection. You could experiment with this method:

document.querySelector('.link').classList.add('hullaballoo');

as an alternative.

Answer №2

Your approach in trying to modify the class of all links is not efficient with your current code.

Instead, I recommend using the following:

event.currentTarget.classList.toggle('hullaballoo');

The event.currentTarget will always refer to the link that was clicked.

If you want all links to have the "hullaballoo" class when one is clicked, you can use:

<a v-for="link in 3" 
   href="#probably-actually-want-a-button"
   @click.prevent="allSelected = !allSelected"
   :class="{ hullaballoo: allSelected }">
   Link {{ link }}
</a>

However, this method does not fully leverage the capabilities of Vue. It's more DOM-focused thinking. Ideally, you should be modifying these classes based on a certain state you're in. To provide a more tailored solution, please clarify your question further.

Answer №3

To retrieve all matching elements in the document, the approved solution can be used.

If you only need to target those within your component, you can achieve this by following these steps:

this.$el.getElementsByClassName('link')

https://v2.vuejs.org/v2/api/#vm-el

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

Help needed with parsing nested JSON using the $.each function

Here is a JSON response sample that needs to be parsed in a more generic manner, rather than using transactionList.transaction[0]. "rateType": interestonly, "relationshipId": consumer, "sourceCode": null, "subType": null, "transactionList": { "transac ...

Creating image filters using an object in jQuery

I am faced with a challenge where I have multiple image tags nested within a div that has the class google-image-layout. Each image is equipped with various data attributes, including: data-anger="0" data-disgust="0" data-facedetected="0" data-fear="0" da ...

Creating a merged object from a split string array in TypeScript

I possess an array containing objects structured as follows; const arr1 = [ {"name": "System.Level" }, {"name": "System.Status" }, {"name": "System.Status:*" }, {"name": "System.Status:Rejected" }, {"name": "System.Status:Updated" } ] My object ...

Can you explain the significance of "javascript:void(0)"?

<a href="javascript:void(0)" id="loginlink">login</a> The usage of the href attribute with a value of "javascript:void(0)" is quite common, however, its exact meaning still eludes me. ...

Steps for capturing a screenshot of the canvas while utilizing the react-stl-obj-viewer component

I recently started using a component called react-stl-obj-viewer to display a 3D STL image. The rendering of the image itself is working fine. However, I encountered an issue when trying to move the rendered image around and implement a button for capturin ...

Using jQuery ajax in PHP, the ability to remove retrieved information from a different page is a

I'm currently working on a jQuery AJAX PHP application that allows for adding, deleting, and displaying records using switch case statements to streamline the code. Everything seems to be functioning correctly with inserting and displaying records, bu ...

Can a blob file be transformed into base64Data using Javascript specifically in Ionic and Angular frameworks?

https://i.stack.imgur.com/3aMyx.png[ async FileZip() { const code = await fetch("./assets/input.txt") var blob = await downloadZip([code]).blob() console.log(blob); function blobToBase64(blob: Blob): Observable<string> { r ...

Unable to authenticate client response using passportjs jwt

Looking to set up login using passport-JWT. able to successfully sign up and log in, with a token generated upon logging in and sent back to the client application. However, after the authentication request reaches the app post-login, it seems like nothin ...

How can Typescript help enhance the readability of optional React prop types?

When working with React, it is common practice to use null to indicate that a prop is optional: function Foo({ count = null }) {} The TypeScript type for this scenario would be: function Foo({ count = null }: { count: number | null }): ReactElement {} Wh ...

Generate a string that will be utilized to interpret a JSON response

I can't seem to extract a specific element from a json using a dedicated function. Can someone please assist me with this issue? Here is the fiddle that I have created for reference: http://jsfiddle.net/jonigiuro/N5TTM/2/ CODE: var data = { "res ...

I am looking to develop a customizable table where the user can input their desired information

Looking to create an HTML page featuring a 10x10 table with alternating red and green squares. After loading the page, a pop-up window will prompt the user to input a word, which will then appear only in the red squares of the table. While I've succes ...

The issue with displaying Fontawesome icons using @import in CSS-in-JS was not resolved

I recently changed how I was importing Fontawesome icons: src/App.css @import "@fortawesome/fontawesome-free/css/all.css";` After shifting the @import to CSS-in-Js using emotion: src/App.js // JS: const imports = css` @import "@fortawes ...

Leveraging the power of AWS API Gateway and Lambda for seamless image upload and download operations with Amazon

I have successfully created a lambda function to handle image uploads and downloads to s3. However, I am encountering difficulties with the proxy integration from the API Gateway. Despite reviewing the documentation and looking at this specific question ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

Parsley JS: A Solution for Distinct IDs

I have a form that contains multiple select boxes, and I need to ensure that no two select boxes have the same value selected. In simpler terms, if select box 1 is set to value 2 and select box 4 is also set to value 2, an error should be triggered. While ...

Tips for obtaining the sources of every image on a webpage and consolidating them in a single section

My goal is to preload all images on a webpage into a single division before the page loads. For example, if there are 5 images on the page (eg1.png, eg2.jpg, eg3.bmp, eg4.jpg, eg5.png), I want them to be contained within a div with the id 'pre'. ...

Ways to retrieve a property that is dynamically generated within a React component

In the code snippet below, I have registered the TextField name as M1.${index}.M13-M14 and it is marked as required. However, I am unable to locate the property accessor using errors[`M1.${index}.M13-M14`]?.type, which prevents the error from being gener ...

Is it possible to retrieve data from Local Storage using user_id and SessionId, and if so, how can it be done?

I have some data in an interactive menu created with iSpring, which includes a feature for local storage to save the last viewed page. I also have a system for logging and need to associate this local storage with user_id or sessionid. I found some informa ...

Trouble with Callback firing in Select2's 'Infinite Scroll with Remote Data' feature

After reviewing the tutorial on the Select2 project page, I am implementing a feature to load additional records as the user scrolls to the end of the results. <script> $(document).ready(function() { $('#style_full_name').select2({ ...

Obtain a collection of keys that share identical values

In my JavaScript code, I have an array of objects structured like this: objArray = [ {"date":"07/19/2017 12:00:00 AM","count":"1000","code":"K100"}, {"date":"07/21/2017 12:00:00 AM","count":"899","code":"C835"}, {"date":"07/23/2017 12:00:00 AM","cou ...