You can use the jQuery .filter()
method to first check if the element clicked has the class .one
, if so, add .two
if not continue.
$('.square').on('click', function() {
$(this).filter('.one').addClass('two').end().addClass('one');
});
$('.square').on('click', function() {
//show classes
console.log( this.className );
$(this).filter('.one').addClass('two')
.end().addClass('one');
});
.square {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>
Another approach would be to use event delegation, considering $('.square.one')
appears like an element added after DOM ready, but you don't want to go that high up in the DOM tree as that may cost you. So you may use the parent of the target element instead of document
:
$('.square').on('click', function() {
$(this).addClass('one');
})
.parent().on('click', '.one', function() {
$(this).addClass('two');
});
$('.square').on('click', function() {
$(this).addClass('one');
//show classes
console.log( this.className );
})
.parent().on('click', '.one', function() {
$(this).addClass('two');
});
.square {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>