Home > Software design >  Removing all classes in a container with javascript
Removing all classes in a container with javascript

Time:09-22

I'm trying to remove all the classes inside a parent element, the structure looks like the following

<div id="middleCol">
  <section class="toggleSection" id="step1" v-on:click="toggleStep($event)" ref="step1">
    <small>Step 1</small>
    <h5>Flight Details</h5>
  </section>

  <section class="toggleSection"  id="step2" v-on:click="toggleStep($event)" ref="step2">
    <small>Step 2</small>
    <h5>Traveler Info</h5>
  </section>

  <section class="toggleSection"  id="step3" v-on:click="toggleStep($event)" ref="step3" >
    <small>Step 3</small>
    <h5>Payment</h5>
  </section>
</div>

basically these are tabs and I only want to apply an active class to one div at a time, my plan is to remove all classes then add the active class to whatever tab is clicked using an event but I'm getting an error that the className property on the other child elements doesn't exist, the function works to add classes just not to remove them, I have seen a few jquery solutions but I was hoping to find a vanilla one

any help is appreciated :)

here is the function I am trying to use

function toggleActive(event){
  let element = event.currentTarget
  let parent = element.parentNode.children;
  console.log(element)
  console.log(parent)
           
  for (let child in parent){
    parent[child.value].className = ''
  }
  element.classList.add("toggleSectionActive");
}

CodePudding user response:

Try to to bind class and use v-for for sections:

new Vue({
  el: '#demo',
  data(){
    return {
      toggled: 0,
      sections: [
        {id: 0, name: 'Step 1', desc: 'Flight Details'},
        {id: 1, name: 'Step 2', desc: 'Traveler Info'},
        {id: 2, name: 'Step 3', desc: 'Payment'}
      ]
    }
  },
  methods: {
    toggleStep(id){
      this.toggled = id
    }
  }
})
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div id="middleCol">
    <section :class="section.id === toggled && 'active'" v-for="section in sections" :key="section.id" @click="toggleStep(section.id)">
      <small>{{ section.name }}</small>
      <h5>{{ section.desc }}</h5>
    </section>
  </div>
</div>

  • Related