Balchandar Reddy
Balchandar Reddy

Reputation: 112

styling for all elements except for a div and all divs inside it

$('#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>

I want the css not to be applied for the nested divs of div with id=2. Any suggestions?

Upvotes: 3

Views: 54

Answers (3)

Ehsan
Ehsan

Reputation: 12959

A) if your mean be #3 only:

default value for background-color is transparent. you do not set background-color for #3 for this reason it get transparent(in this case, you see blue color,because #2 have background-color:blue).

your selector is correct just insert initial value for divs:

div {
  background-color:#fff;
}

Demo

B) If your mean be #2 and his childrens:

  • Do not start the ID with the number(I change #2 to #a2)

Use this:

#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>

Upvotes: 1

Suri
Suri

Reputation: 16

$('#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>

Upvotes: 0

Nick
Nick

Reputation: 417

You have to exclude div#2 in this way:

$('#main > div').not('#2').each(function() {
    $(this).css('background-color', 'blue');
});

Or more simply:

$('#main > div').not('#2').css('background-color', 'blue');

Pure CSS:

#main > div:not(#2) {
    background-color: blue;
}

Upvotes: 2

Related Questions