Why is the jQuery selector ':not' not working?

Viewed 42

I want to select a div with an id or class and at the same time exclude a id or class inside the div and get the content as string.

Here is my markup:

<div id='main-content'>
  <div>test 1</div>
  <div class='ignore'>ignore test</div>
</div>

I tried $('#main-content:not(.ignore)').text();

It is selecting the div with the id main-content, but the class ignore is still in the string. What am I doing wrong?

Here is a fiddle example.

1 Answers

You are selecting the element with the id and saying that should not have the class. It should be done on the child elements.

console.log($("#main-content > *:not(.ignore)").text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='main-content'>
  <div>test 1</div>
  <div class='ignore'>ignore test</div>
</div>

Related