0

Basic question but still I cannot figure out how to add an extra class based on @click. I still get error: Cannot read property 'add' of undefined"

methods: {
    hideItems() {

        document.getElementsByClassName('sold').classList.add('hide')
       }
    }

2 Answers 2

2

You can add the :class="{ hide: hidden }" property on your element, where hidden is a boolean property of the Vue component. This will toggle the hide class on the element.

new Vue({
  el: "#app",
  data() {
    return {
      hidden: false,
    };
  },
  methods: {
    toggle() {
      this.hidden = !this.hidden;
    },
  },
});
.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="toggle">
  Toggle visibility
  </button>
  <div :class="{ hide: hidden }">
    Hello
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

this is the correct answer
0

getElementsByClassName return HTMLCollection so you need to loop through that collection.

that should do it:

methods: {
    hideItems() {
        const items = document.getElementsByClassName('sold');

        for(item of items){
           item.classList.add('hide');
         }
       }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.