Mastering the art of manipulating the Document Object Model in Vue.js

I have a situation where I am using v-for to display a lot of data in JSON as individual buttons. My goal is to change the background color of the button when it is clicked. I plan to use @click to bind a function to each button, and within that function, perform the following action:

theButtonDOM.style.backgroundColor = 'black';

How can I access the DOM element of the button generated by v-for? Alternatively, are there any other solutions to solve this issue of changing the background color?

Answer №1

Whenever a click event is triggered in a Vue template, you have the ability to access the event by including the special variable $event as an argument in the function.

<button @click="my_method($event, other_argument)"></button>

You can then retrieve the target of the event within the method:

methods: {
    my_method(event, other_parameters) {
        let button = event.target
}
}

Even if you simply bind the method to the @click event without any arguments, you can still access the event as your first parameter.

<button @click="my_method"></button>
...
methods: {
    my_method($event) {
        let button = $event.target
}
}

You are now able to interact with your button accordingly.

For additional information, refer to this stackoverflow question and the Vue documentation.

Answer №2

To utilize the $event variable, follow these steps:

<button @click="changeColor($event)"></button>

In your method implementation:

this.changeColor = function(evt){ evt.target.style.backgroundColor = 'red'; }

Answer №3

If you want to change the class of an item when it is clicked, you can utilize @click and v-bind:class. By using these directives, you can store the index of the clicked item in a variable called selectedItem, which will then automatically apply a specific class to the item with the corresponding index.

new Vue({
  el: '#app',
  data: {
    selectedItem: ""
  },
  computed:{},
  methods: {}
  }
)
.selectedItemClass {
  background-color:green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">

  <div v-for="(item,index) in ['aa','bb','cc']"
    v-bind:class="{  selectedItemClass : (selectedItem === index) }"
    @click="selectedItem = index"
  >{{item}}</div>
  
</div>

Answer №4

It seems like you are looking to have the buttons function as independent switches rather than a radio group, similar to what was suggested by @eag845 in another response.


An approach could be to introduce a 'clicked' boolean property to your JSON Objects.

arrayOfJSONObjects.forEach(object => object.clicked = false); // Create and set 'clicked' attribute to false

You can then utilize this property as a condition to apply a CSS class using v-bind:class or :class. Additionally, you can toggle this property within the @click event handler or any other relevant function you define within @click.

<button
    v-for="btn in arrayOfJSONObjects"
    :class="{ 'button--activated': btn.clicked }"
    @click="btn.clicked = !btn.clicked"
>{{btn.foo}}</button>

CSS Styling:

.button {
  background-color: white;
}
.button--activated {
  background-color: black;
}

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

Initializing an HTML5 video player directly from an Array

I am trying to populate a video player on my webpage with an array of videos. Here is the code I have so far: var current = 0; var videos = ["01", "02", "03", "04"]; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomInde ...

What exactly is the task of the Angular compiler?

Someone asked me this question today and I couldn't come up with a proper response. When it comes to deploying, Typescript transpiles to JS and then there is tree shaking, "less" (optional), and various optimizations involved. However, is any of this ...

Having trouble with loading textures in Three.js?

I'm facing an issue while trying to apply a texture to my mesh using three.js. Instead of the expected loaded texture, I am just seeing a plain black object. I followed the examples provided in the three.js documentation ( - Example) and also tried va ...

What is the best way to line up three divs horizontally and center the contents inside each one?

I'm brand new to CSS and need some help simplifying things. I am trying to create 3 divs that are all the same size, placed next to each other, with centered content in each one. Currently, I have a central div with a rotating image, and on the left a ...

Fixing the issue: "Tricky situation with JavaScript not working within Bootstrap 4's div tag while JS functions properly elsewhere"

Currently, I'm working on implementing a hide/show function for comments using JavaScript. Fortunately, I was able to find a helpful solution here (thanks to "PiggyPlex" for providing the solution on How can I hide/show a div when a button is clicked? ...

Exporting Datatable to Excel may cause line breaks

I have structured my project in the following manner: https://jsfiddle.net/Eufragio/u342qgoz/1/ When I export to excel, I require a better layout or a more visible method to display my results $(document).ready( function () { var table = $('#exam ...

React Material UI issue: You cannot render objects as a React child. If you intended to display a group of children, make sure to use an array instead

I am encountering an issue with the code provided below and despite trying various fixes, I am unable to resolve it. componentDidMount() { axios.get('http://localhost:8080/home') .then((response) => { this.setState({ ...

When working with DNN, I attempted to redirect using JavaScript code, but found that I continue to see the same page after the form submission code

Here is the code I am using to submit a form. When the button is clicked, it will trigger the Checkout() function. function postURL(url) { var form = $('<form action="' + url + '" method="post">' + "<input type=& ...

Is there a more effective method to return a response apart from using a redundant function?

function unnecessaryFunction(){ let details: SignInDetails = { user: user, account: account, company: company }; return details; } I am being told that the details value is unnecessary. Is there ...

The modification of Javascript content type occurring following URL Rewrite

I'm currently working on setting up a Reverse Proxy with ARR and URL rewrite in order to achieve the following redirection: Source: http://localhost/test Destination: http://localhost:83/ The goal is for the final URL displayed to be same as the so ...

Select the top row of a table when the checkbox is ticked to emphasize it

Previously, I tackled a challenge on a webpage using jQuery where checkboxes in a table needed to be selected based on specific data attributes. Essentially, if one checkbox in a row was selected, the rest of the checkboxes would be disabled if their data ...

The issue arises when RadioBoxes do not submit properly after their `check` status is altered using JQuery

My form contains multiple radio boxes whose "checked" status I modify based on user interaction. Upon initial page load and submission without any changes, the POST request correctly includes the value of the checked radio box. However, when I use JQuery ...

Attempting to update state on a component that is no longer mounted

There are many instances in my components where I find myself needing to execute the following code: function handleFormSubmit() { this.setState({loading: true}) someAsyncFunction() .then(() => { return this.props.onSuccess() }) . ...

The variable in Vue.js is failing to update, resulting in a "variable is not defined" error

I've been attempting to display the updated value of the totalQuestions variable in the HTML, but I keep encountering the following error. Can someone point out where I went wrong? https://i.sstatic.net/mEEMS.jpg HTML <label><span class="r ...

Utilizing map in React JS to simultaneously execute various functions

Currently, I am working on parsing an array in React JS. Here is an example of my array (it can change dynamically): [ "save", "save", "not", "save"] The objective is to create a function that triggers another funct ...

Pattern for Ajax callback in Javascript

I'm facing an issue with the code snippet below. var bar = { ajaxcall : function(){ var _obj = {}; $.ajax({ headers: { 'Content-Type': "application/json; charset=utf-8", 'da ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Limiting character count in jQuery using JSON

I am trying to manipulate the output of a snippet of code in my jQuery: <li> Speed MPH: ' + val.speed_mph + '</li>\ that is being pulled from a JSON endpoint and currently displays as: Speed MPH: 7.671862999999999 Is there a ...

What is the best way to invoke a function using a string as its name?

In my grid configuration function, I am assigning column definitions. One key, valueGetter, requires a function to be called to fetch the column value. The issue I am encountering is that the API returns this value as a string. When I try to set it using ...

Interacting with HTML elements in Java programming

I am facing a challenging situation that requires some brainstorming. I would greatly appreciate any advice or guidance in the right direction. My goal is to incorporate a Google Map into my Java Swing project, with the map being specified as a URL wit ...