jQuery addClass example
Change class name on click in jQuery
HTML
<div class="wrap">
<div class="before">Before</div>
<button class="add">Добавить</button>
</div>
CSS
.clone{
width: 300px;
height: 50px;
background: lightblue;
margin-bottom: 10px;
}
.before{
width: 300px;
height: 50px;
background: lightgreen;
}
JavaScript
let wrap = document.querySelector('.wrap');
class Clone {
constructor(wrap){
this.wrap = wrap;
this.itemTpl = '<span>Hello </span><b>KrisIris!</b>'
this.index = 1;
let btn = wrap.querySelector('.add');
btn.addEventListener('click', () => this.add());
}
add(){
var el = document.createElement('div');
el.className = 'clone';
el.innerHTML = this.itemTpl + ' ' + (this.index++);
console.warn(el);
this.wrap.parentNode.insertBefore(el, this.wrap);
}
}
let clone = new Clone(wrap);