Add class to element

别说谁变了你拦得住时间么 提交于 2019-12-02 14:08:02

First of all don't use same id on different elements, id's must be unique and try this:

jQuery:

$('.menuitem').click(function() {
    $('.menuitem').removeClass('active');
    //removes active class from all menu items

    $(this).addClass('active');
    //adds active class to clicked one
});

html:

<div id="tab1" class="menuitem"></div>
<div id="tab2" class="menuitem"></div>

css: you don't need to define same properties to active class, just define the difference:

.active { background-color: red; }

.menuitem {
  width: 170px;
  height: 70px;
  float: right;
  background-color: white;
}

You can not have same id for two divs in HTML. Try changing your HTML like this.

<div id="menuitem1" class="menuitem tab1"></div>
<div id="menuitem2" class="menuitem tab2"></div>

.active {
background-color: red;
}

.menuitem {
width: 170px;
height: 70px;
float: right;
background-color: white;
}

The other issue might be that you're running your jQuery function before the div element exists.

So either, move the code

$(".tab1").addClass('active');

below the div's you want to change, or wrap it in a document ready function.

$(document).ready(function(){
    $(".tab1").addClass('active');
});

which will wait till the dom has been created before running your code.

First off, ids should always be unique.

The cause of your issue however, is css specificity. An id rule is more specific than a class one. Try this instead.

#menuitem.active {
width: 170px;
height: 70px;
float: right;
background-color: red;
}

#menuitem {
width: 170px;
height: 70px;
float: right;
background-color: white;
}

Keep in mind though that this will work to overcome the specificity issue. It does not address the fact that you need to get rid of your duplicated ids.

CSS Specificity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!