$('#main div').not('#2 > #3').each(function() {
$(this).css('background-color', 'blue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div id="1">
<div>Some text in paragraph 1</div>
<div>Some text in paragraph 1</div>
</div><br>
<div id="2">
<div id="3">Some text in paragraph 2</div>
<div>Some text in paragraph 1</div>
</div><br>
<div id="3">
<div>Some text in paragraph 3</div>
<div>Some text in paragraph 1</div>
</div><br>
</div>
我希望css不会被id=2
应用于div的嵌套div。有什么建议吗?
答案 0 :(得分:2)
您必须以这种方式排除div#2:
$('#main > div').not('#2').each(function() {
$(this).css('background-color', 'blue');
});
或更简单:
$('#main > div').not('#2').css('background-color', 'blue');
纯CSS:
#main > div:not(#2) {
background-color: blue;
}
答案 1 :(得分:1)
A)如果您的意思仅为#3
:
background-color
的默认值为transparent
。您没有为background-color
设置#3
因为这个原因transparent
(在这种情况下,您会看到blue
颜色,因为#2
有background-color:blue
})。
你的选择器是正确的只需插入div
的初始值:
div {
background-color:#fff;
}
B)如果你的意思是#2
和他的孩子:
#2
更改为#a2
)使用此功能:
#main>div:not(#a2) {
background-color: blue!important;
}
#main>div:not(#a2) {
background-color: blue!important;
}
<div id="main">
<div id="1">
<div>Some text in paragraph 1</div>
<div>Some text in paragraph 1</div>
</div><br>
<div id="a2">
<div id="3">Some text in paragraph 2</div>
<div>Some text in paragraph 1</div>
</div><br>
<div id="3">
<div>Some text in paragraph 3</div>
<div>Some text in paragraph 1</div>
</div><br>
</div>
答案 2 :(得分:0)
$('#main>div').not('#2').each(function() {
$(this).css('background-color', 'blue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div id="1">
<div>Some text in paragraph 1</div>
<div>Some text in paragraph 1</div>
</div><br>
<div id="2">
<div id="3">Some text in paragraph 2</div>
<div>Some text in paragraph 1</div>
</div><br>
<div id="3">
<div>Some text in paragraph 3</div>
<div>Some text in paragraph 1</div>
</div><br>
</div>