Reputation: 251
I have this html:
<div class="container">
<div id="cell1" class="cell"><div class="content"></div></div>
<div id="cell2" class="cell"><div class="content"></div></div>
<div id="cell3" class="cell"><div class="content"></div></div>
</div>
CSS:
.container {
width: 300px;
height: 300px;
background-color: green;
}
.cell {
background-color: red;
}
#cell1 {
width: 70px;
height: 70px;
}
#cell2 {
width: 70px;
height: 70px;
}
#cell3 {
width: 70px;
height: 70px;
}
.white {
background-color: white;
}
.yellow {
background-color: yellow;
}
.content {
width:40px;
height:40px;
background-color:blue;
}
Javascript:
$(document).on('click', '.cell', function(e) {
$(this).parent().children().removeClass('white');
$(this).parent().children().children().removeClass('yellow');
$(this).addClass('white');
$(this).find('.content').addClass('yellow');
});
The problem I am having now is addClass('yellow') has no effect. However, if I delete the background-color in content class, it works. Any thoughts why?
jsFiddle link: http://jsfiddle.net/rexwang/FWh6E/
Thanks for the answers, it works! But I really don't like using addClass and removeClass, is it posible to use e.currentTarget.id to achieve the same goal?
Upvotes: 4
Views: 658
Reputation: 43823
The .addClass()
is working but because of the way CSS rules are applied, the .content
selector has more weight than the .yellow
single class selector - see CSS specificity for a Star Wars themed explanation of specificity.
In the CSS documentation the final clause is being used to determine which rule is applied.
Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.
So you could either swap the order of the rules in the CSS file, moving .yellow
after .content
, or give the .yellow
selector more weight by adding another selector to the chain, for example:
.content.yellow {
background-color: yellow;
}
Upvotes: 4
Reputation: 15387
Try this
Change CSS yellow
as below:
.yellow {
background-color: yellow!important;
}
Upvotes: 1
Reputation: 133453
JSFIddle link: http://jsfiddle.net/Cj4PT/
Your code
.yellow {
background-color: yellow;
}
Change to
.yellow {
background-color: yellow!important;
}
.content
background style was overriding .yellow
style
Upvotes: 1
Reputation: 28763
put !important for this
.yellow {
background-color: yellow !important;
}
Try this FIDDLE
Upvotes: 1
Reputation: 145458
It works but the .yellow
background style is overriden by the .content
background style, since in the stylesheet .content
class goes after .yellow
.
One way is to swap these classes in the CSS.
DEMO: http://jsfiddle.net/FWh6E/2/
Upvotes: 4