0

I need to select all the elements in my container except for a particular child element and its descendants.

In the following example I want My name is Donald and I am a duck to be excluded by the jQuery that highlights everything else in the container div.

The issue is that the selector .container :not(.intro) seems to only exclude My name is Donald. Is there a way to do this?

$(document).ready(function() {
  $(".container :not(.intro)").css("background-color", "yellow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<h1>Welcome to My Homepage</h1>
<div class="container">
  <div class="intro">My name is Donald
    <div>I am a duck</div>
  </div>
  <div>I live in Duckburg.</div>
  <div>My best friend is Mickey.</div>

</div>

jsfiddle

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Urbycoz
  • 7,247
  • 20
  • 70
  • 108
  • I disagree with this question being closed as a duplicate. The other question is entitled "What is the difference between '>' and a space in CSS selectors?" How can you find that question unless you already know the answer to mine? – Urbycoz Nov 29 '19 at 10:53
  • 1
    *How can you find that question unless you already know the answer to mine?* --> this is the purpose of the duplicate. I know the answer so I can find that question. By knowing the difference and the existance of such selector you have your answer. As a side note, we don't close a question only based on the title – Temani Afif Nov 29 '19 at 11:01
  • Ok, so it's not so much a "duplicate" as covering the same topic from a slightly different angle? I realise you don't close questions based on the title, but I was making the point that the question is explaining the concept I didn't know existed. – Urbycoz Nov 29 '19 at 11:09

1 Answers1

3

You can add > between .container and :not(.intro) This will result in that it will only select direct children of .container that don't have the class .intro

$(document).ready(function() {
  $(".container > :not(.intro)").css("background-color", "yellow");
});

Demo

$(document).ready(function() {
  $(".container > :not(.intro)").css("background-color", "yellow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<h1>Welcome to My Homepage</h1>
<div class="container">
  <div class="intro">My name is Donald
    <div>I am a duck</div>
  </div>
  <div>I live in Duckburg.</div>
  <div>My best friend is Mickey.</div>

</div>
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77