0

I need to apply not(.pseudo-element) filter using js but not sure how to add it so far i've manage to extract #app from the DOM using:

const app = document.getElementById('app')
    
app.style.filter = 'brightness(0.5)'

Now my goal is to apply this brightness to all childs with exception for one, how to achieve it using js

Andon Mitev
  • 1,354
  • 1
  • 11
  • 30
  • Does this answer your question? [Setting CSS pseudo-class rules from JavaScript](https://stackoverflow.com/questions/311052/setting-css-pseudo-class-rules-from-javascript) – Samball Mar 21 '22 at 09:44
  • You want to select pseudo element like `:before`/`:after` or some child with class `.pseudo-element`? – Justinas Mar 21 '22 at 09:45
  • I need from my children to select my top parent element with id `#app` and then apply `filter` to that element for all childrens except for one with class `.pseudo-element` ( or basically the child that is executing this logic ) – Andon Mitev Mar 21 '22 at 09:49

2 Answers2

0

You can try the :not() selector as shown below which will return all child elements from app excluding elements having .pseudo-element class.

app.querySelectorAll('*:not([class="pseudo-element"])');

Another way to write the same is as belows:-

app.querySelectorAll('*:not(.pseudo-element)');

The :not(selector) selector also accepts commas

app.querySelectorAll('*:not(.pseudo-element,.pseudo-element-2)');
shotgun02
  • 756
  • 4
  • 14
  • Code without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See [How to Answer](https://stackoverflow.com/help/how-to-answer). – Sfili_81 Mar 21 '22 at 12:51
0

You could use shotgun02's answer or something like this:

const elements = [...app.querySelectorAll('*:not(.pseudo-element)')];

elements.forEach((element) => {
  element.style.filter = 'brightness(0.5)';
});

In the example above I'm using spread syntax ([...app.querySelectorAll()]) because I personally prefer to work with Objects instead of NodeList but that's a personnal preference.

Another approach would be to use the .classList() method :

const elements = [...app.querySelectorAll('*')];

elements.forEach((element) => {
  if (!element.classList.contains('pseudo-element')) {
    element.style.filter = 'brightness(0.5)';
  }
});

Keep in mind that the best approach is probably to do the same thing with CSS if you don't really need JS for that.

* {
  filter: brightness(0.5);
}

.pseudo-element {
  filter: none;
}

Manoz
  • 96
  • 8