Add a class to a corresponding element without any other specific class

Whenever a user clicks on the body
I would like to add a class to a certain element, as long as that element doesn’t have a specific class. The issue is, I re-use this element and some of these elements will have that specific class I mentioned and other will not. If one element has this class, with my current code, no element will have new class added.

Here is a fiddle showing the behaviour
.

Example:

$('body').on('click', function(){
    if ($('.box').hasClass('red') && !$('.box').hasClass('stay-red')) {
        $('.box').addClass('blue');
    }
});
html, body {
    background: lightblue;
    height: 100%;
}
.box {
    height: 20px;
    width: 20px;
    margin-bottom: 10px;
}
.red {
    background: red;
}
.blue {
    background: blue;
}
$(function(){

$('body').on('click', function(){
    $('.box').each(function(){
        if ($(this).hasClass('red') && !$(this).hasClass('stay-red')) {
          $(this).addClass('blue');
        }
    })

});

})
html, body {
    background: lightblue;
    height: 100%;
}

.box {
    height: 20px;
    width: 20px;
    margin-bottom: 10px;
}

.red {
    background: red;
}

.blue {
    background: blue;
}
  
    
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Add a class to a corresponding element without any other specific class

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录