Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change called class in javascript when button is click?

I have a div which is

<div class="add1"></div>

I want the add1 become add+thenumber of length example:

var n= $('.add1').length + 1;  
$('.add1').click(function(){

so what I did is

$('.add+n').click(function(){

but it doesnt work, please help me :(

like image 332
user101 Avatar asked Dec 13 '15 05:12

user101


1 Answers

You can store the number in a data attribute and increment on every click. Change the class attribute from the data attribute value.

HTML

  <div id="myDiv" data-num='1' class="add1">click me</div> 

JS

document.getElementById('myDiv').addEventListener('click', function(){

var num = Number(this.getAttribute('data-num'));
num++;
this.setAttribute('data-num', num)

this.setAttribute('class', 'add' + num);

});
like image 170
CodeToad Avatar answered Oct 08 '22 09:10

CodeToad