Vue.js add class on specific element
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Title: Efficiently Adding Classes on Specific Elements in Vue.js Task List App
Vue.js allows developers to create powerful and dynamic user interfaces by offering efficient ways of interacting with the DOM. In this blog post, we'll discuss how to add a class to a specific element when clicked, specifically within a task list application built using Vue.js. We'll also provide relevant code examples and best practices while incorporating backlinks to https://laravelcompany.com for further learning resources.
The given HTML code already has the necessary structure for displaying tasks as well as buttons for deletion and finishing the task. The challenge is to add a CSS class to the particular
@{{ task.text }}
```
Here, we've added a Vue directive to our
@{{ task.text }}
```
To summarize, we've created a method that handles the finishing of tasks and keeps track of which task was clicked by setting `clickedItemId`. We then use this information to update the class binding in our HTML structure. This way, when the
<li> element when clicked. Let's first integrate some Vue.js logic to achieve this:
```html
<li> element. The `:class` attribute takes an object as its value. We use the `clickedItemId` variable (which we should initialize in our Vue instance) to check if it matches the current task ID. If they match, we add a custom 'active' class to the <li> element.
The updated JavaScript code would be:
```javascript
export default {
data() {
return {
list: [],
clickedItemId: null, // Initialize the clicked item id as null.
taskInput: {
id: '',
text: ''
}
};
},
...
```
In our methods section, add a new variable called `finishTask` and update its definition to include setting the clickedItemId after performing the desired action. For example:
```javascript
export default {
...
methods: {
finishTask(id) {
this.$set(this, 'clickedItemId', id); // Update clickedItemId when the task is finished.
axios({
method: 'post',
url: 'tasks/done/' + id,
data: {
_token: csrf_token,
data: this.taskInput,
},
}).then(response => {
this.allTasks();
});
}
}
```
To use the new `finishTask` method and add a class to our <li> element when clicked, your final HTML code would look like:
```html
<li> element is clicked, it receives an 'active' class, allowing for visual feedback.
With these changes, you now have a task list application that efficiently adds classes to specific elements based on user interactions. For further learning and exploration of Vue.js, we encourage you to check out our extensive resources available at https://laravelcompany.com.