Home > Mobile >  Apply .not() filter using js
Apply .not() filter using js

Time:03-21

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

CodePudding user response:

Try this ..

app.querySelectorAll('*:not([])');

CodePudding user response:

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;
}

  • Related