Coding Challenge – Implement jQuery’ s addClass and removeClass functions using vanilla JS

Please follow & like us :)

jquery logo
/**
* How would you implement jQuery' s addClass and removeClass 
* functions using vanilla JS? What other variations you can use? 
* Can you pass multiple parameters for classnames ? How will you make these vanilla JS functions asynchronous? Make this component re-usable. 
*/

$('#container')
.addClass('blue')
.addClass('bg-lime')
.addClass('bold')
.addClass('font-medium-italic')
.addClass('border-solid-pink');


<div id='test'></div>
<button id='clicktest'>Test</button>
document.getElementById('test').classList.add('test', 'test1', 'test2');
document.getElementById('test').classList.remove('test1');


document.getElementById('clicktest').addEventListener('click', function() {
  document.getElementById('test').classList.toggle('test');
  console.log(document.getElementById('test'));
});

class changeClass {
  constructor(ele) {
    this.ele = ele;
  }
  async addClass(newclass) {
    newclass.split(' ').forEach( (val)=> {
    this.ele.classList.add(val);
    })
  }
  async removeClass(newclass) {
    this.ele.classList.remove(newclass);
  }
}

const ele = document.getElementById('test');

let newC = new changeClass(ele);
let s = 'newname1 tedt'
newC.addClass(s);
newC.removeClass('test');