0

I try to understand how the :not selector works. First of all i guessed that everything that works inside of a querySelectorAll function works in the same way in css.

What i'm trying to accomplish is to get a list of elements from a page excluding the one i don't need. Thats's why i'm using this small function:

getItems() {
 return document.querySelectorAll('div:not(.sponsored):not(#hot_news) .item-story');
}

The important thing is that every section contain a <li> that has the item-story class, but i want to exclude the ones that are inside of a <div> with the class sponsored and a <section> that has the id hot_news.

In this fiddle you can find an example of what i tried already, it seems to work fine in CSS, but not in JS, and even if it seems to work i don't get why it should.

http://jsfiddle.net/RM8nZ/72/

Stefano Saitta
  • 1,844
  • 1
  • 19
  • 34

1 Answers1

1

:not(foo) bar matches all bar elements which have some ancestor which is not a foo. That does not mean that no ancestor is a foo.

Instead, you should get all .item-story elements and exclude the ones that match .sponsored .item-story, #hot_news .item-story.

var set = new Set(document.querySelectorAll('.item-story'));
var excluded = document.querySelectorAll('.sponsored .item-story, #hot_news .item-story');
for(let el of excluded) set.delete(el);

I used ES6 sets because operations are required to be sublinear (probably constant) on average. However, if you want to support old browsers, use arrays and see JavaScript array difference.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • I was looking for a same solution actually, but using a ___filter___. http://jsfiddle.net/RM8nZ/81/ EDIT: the return value of querySelectorAll is not an Array – Stefano Saitta May 10 '16 at 09:31
  • You have no guarantee the excluded element will be the first match, so you can't use `querySelector` in the callback. It would work properly if you used `querySelectorAll` and iterated it. But that would be a quadratic cost. ES6 sets have better performance. – Oriol May 10 '16 at 09:36