除了div和所有div之外的所有元素的样式

时间:2017-11-13 10:02:38

标签: jquery html css

$('#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。有什么建议吗?

3 个答案:

答案 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颜色,因为#2background-color:blue })。

你的选择器是正确的只需插入div的初始值:

div {
  background-color:#fff;
}

Demo

B)如果你的意思是#2和他的孩子:

  • 请勿使用该号码启动ID(我将#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>