Modifying tag classes dynamically with JavaScript

I am working on creating a list of projects where the user can select one as the default project for future use in other processes.

The issue I am facing is that each project in the list has a unique id and by default, they all have the RegularIcon class attached to them. This is how it is structured:

<span :id="project.id" class="RegularIcon" @click="changeIcon(project.id, projectKey)"></span>

In this code snippet, projectKey represents the index of the current project in the list.

Here is the function I have implemented:

changeIcon: function(projectId, projectIndex) {

  let ClassName = document.getElementById(projectId).className;

  if (ClassName == 'RegularIcon') { 

    var x = document.getElementsByClassName("SolidIcon");
    var i;

    if (x.length != 0) {
      for (i=0; i < this.ProjectsList.length; i++) {
        if (i != projectIndex) { 
          x[i].className = 'RegularIcon'; 
        } else {
          x[i].className = 'SolidIcon'; 
        }
      }
    } else {
      document.getElementById(projectId).className = 'SolidIcon'; 
    }

  } else { 
    document.getElementById(projectId).className = 'RegularIcon'; 
  }

},

My intention was for the user to be able to click on an icon to toggle between filled and unfilled states, with the selected project becoming solid and filled while others return to their regular state.

However, upon testing the functionality, I encountered an error message :

Uncaught TypeError: Cannot set property 'classList' of undefined

Answer №1

Instead of directly manipulating the DOM, you have the option to utilize Vue's class binding feature to assign a specific class based on certain conditions:

<span :class="{ CLASS1: CONDITION1, CLASS2: CONDITION2, ... }">

In your scenario, this binding would look like:

<span :class="{ RegularIcon: CONDITION, SolidIcon: !CONDITION }">

Here, the value of CONDITION is determined by user selection (such as the selected index). For instance, when the icon's index does not match the selected index, the RegularIcon class will be active; conversely, if they do match, the SolidIcon class will be active.

<div v-for="(project, i) in projects">
  <span :class="{ RegularIcon: i !== selectedIndex, SolidIcon: i === selectedIndex }"
        @click="selectedIndex = i"></span>
</div>

new Vue({
  el: '#app',
  data: () => ({
    selectedIndex: -1,
    projects: [
      {id: 1},
      {id: 2},
      {id: 3},
    ]
  }),
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f797a6a4f3d213a213e38">[email protected]</a>"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.2/css/all.css" integrity="sha384-/rXc/GQVaYpyDdyxK+ecHPVYJSN9bmVFBvjA/9eOB+pb3F2w2N6fc5qB9Ew5yIns" crossorigin="anonymous">

<div id="app">
  <div v-for="(project, i) in projects" :key="project.id">
    <span class="fa-ghost"
          :class="{far: i !== selectedIndex, fas: i === selectedIndex}"
          @click="selectedIndex = i"></span>
  </div>
</div>

Answer №2

Consider utilizing the following:

document.getElementById(taskId).classList.add("newClass");
document.getElementById(taskId).classList.remove("oldClass");

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

SCORM: moving between SCOs by clicking a button in the presentation

Currently, I am developing a website that allows users to create presentations. One of the website's features is the ability to export presentations in SCORM format (either 1.2 or 2004). This is my first time working with SCORM and I am currently impl ...

Filter ng-repeat using OR condition for property

I'm trying to filter a list based on a model value entered in a text box. For example: var person={}; person.Id=1; person.Name="Test 1"; person.PetName="Rest 1" var persons=[]; persons.push(person); person.Id=2; person.Name="Test ds"; per ...

Middleware in the form of Try and Catch can be utilized to handle errors and

Currently, I am working on developing a backend using node.js with Express. My main goal is to effectively handle any potential status 500 errors that may arise. router.put('/test', async (req, res) => { try { return res.send(await r ...

What's preventing me from utilizing Leaflet Map on Next.js despite attempting Dynamic Import?

When using Leaflet, it requires the global window object which is not available on SSR (Server-Side Rendering) and can cause an error stating "window is not defined". I have tried extensively to find a solution, and the only method I found was to use dyna ...

What is the best way to add data to a URL in an ActionResult Method using window.location.href?

I am having trouble understanding how to retrieve data using window.location.href = '/Product/Success/'+data.OrderTrackNo+'';. I am able to get data using ajax, but it seems different when retrieving data with window.location.href, whic ...

Encountered a problem while trying to inherit from the BrowserWindow class in

I utilized the https://github.com/SimulatedGREG/electron-vue template to craft a vue electron blueprint. Alongside the primary process index.js, I fashioned a file named MainWindow.js which holds the subsequent code: import { BrowserWindow } from 'el ...

`In HTML, trigger blocks based on the number chosen by the user`

I am working on creating a web page where users can select the number of friends they have, and based on that input, a corresponding number of invisible boxes will be triggered. For example, if a user selects 3 friends, 3 boxes will appear for them to ente ...

Using an image as a button in Vue.js: A step-by-step guide

I'm currently working on creating a login button within a single-file-component using Vue.js in my Rails application with a Vue.js front-end. The purpose of this button is to redirect users to an external login page when clicked. I am wondering how I ...

Is the translation pipe in Angular 5 impure?

I'm currently utilizing ngx-translate. Can you tell me if the translation pipe is considered pure or impure? Also, would it be more beneficial to use the directive syntax translate="X" instead? ...

The (ReactJS + Redux) form fails to load when the /new segment is appended to the URL

I'm currently working on a project using React, Redux, and Rails. I've encountered an issue with loading the form. In my App.js file, I have set up a Router that defines the routes. import React, { Component } from 'react'; import { Br ...

Is it possible for Nextjs routing catchAll to coexist with a slug folder within a route?

When converting my pages to ISR, I encountered an issue with handling params and dynamic routes. One example is where article/?pageNumber=2 needs to be rewritten as article/2 in middleware for improved performance. However, this change in routing structure ...

Obtaining response object when encountering 401 error in AngularJS

I am currently working with Angular 1.6.4, Express 4.15.2, and express-session. My goal is to identify whether a user is unauthorized to access a specific route by checking for the existence of the req.session.user parameter. If the user is not authorized, ...

Ways to resolve: The JSX component does not contain any construction or call signatures

I've been grappling with a persistent issue regarding the creation of custom elements dynamically in React TypeScript. If you're curious, you can check out the question here. const generalButtons: MenuButton[] = [ { text: "New Cl ...

Instructions for copying a vuedraggable item into the nested children list of its sibling element

Visit this link for more information Everything seems to be working with the pull operation, but as soon as I switch the pull prop from 'true' to 'clone', an error pops up. An issue occurred: NotFoundError - Failed to execute 'i ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Modifying the value of a property in an object array created using the map method is ineffective

I have a collection of objects: https://i.sstatic.net/XNrcU.png Within the collection, I wished to include an additional property to the objects. To achieve this, I utilized the map function: returnArray = returnArray.map((obj) => { obj.active = "fal ...

Encountering difficulties in sending a JavaScript array through jQuery ajax request

I'm feeling hesitant to ask this, but I can't figure out why my code isn't working. Here's what I have: <script> var formArray = new Array(); formArray['start'] = "one"; formArray['stopat'] = "two"; formArray ...

Issue: ENOENT - The specified file or directory cannot be found while scanning in a discord bot

Recently, I decided to try my hand at creating discord bots even though I am new to it. After watching a tutorial and copying the code, I encountered an error that has me stumped: node:internal/fs/utils:347 throw err; ^ Error: ENOENT: no such ...

Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user. Below is the code snippet that I am working with: func ...

Updating the scope variable in an AngularJS directive

Recently delving into Angular, I encountered an issue: I have both a list view and a details view with tags. To facilitate navigating between the two views and loading new elements from a service upon click events, I created a directive. My aim is to also ...