Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change style of element in click if its in a for loop in Javascript + Vue?

If I have an element like this that is in a for loop:

<p class="description" id="description" @click="onClickDescription">{{ review.text }}</p>

meaning that there is more than one of these elements, how can I change the style of the element that was clicked.

I have this function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

onClickDescription(e) {
  console.log(e)
  let d = document.getElementById('description');
  d.style.webkitLineClamp = 99;
}

But this will change the style of all my <p> elements instead of just the one I clicked. How can I get around this?

>Solution :

You can use index or id if you have it in review object:

new Vue({
  el: '#demo',
  data() {
    return {
      reviews: [{text: 'aaa'}, {text: 'bb'}, {text: 'ccc'}],
      selected: null
    }
  },
  methods: {
    onClickDescription(i) {
      this.selected = i
    }
  }
})
.description {
  color: green;
}
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="(review, i) in reviews" :key="i">
    <p class="description" :class="i === selected && 'active'" @click="onClickDescription(i)">{{ review.text }}</p>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading