0

Is there a way to shorten querySelector result and perform an operation on its result? Ideally in one line?

Imagine having an element:

<div id="el">A</div>

And corresponding JavaScript code:

const el = document.querySelector("#el");

el ? el.style.display = "none" : null;

Assuming div#el may or may not be rendered on the page (hence ternary operator), is there a way to shorten above logic to one line?

Dom
  • 645
  • 6
  • 17
  • 1
    I think the only way is to not create `const` and use it directly in short code. if you need `const` your method is already the best – Simone Rossaini Mar 02 '21 at 13:48
  • 1
    You can do `document.querySelector("#el")?.style.setProperty("display", "none")`. But why do you need to shorten that code int he first place? This starts getting into the realm of hacks. – Thomas Mar 02 '21 at 15:14

4 Answers4

0

why not just

if (document.querySelector("#el")) document.querySelector("#el").style.display = "none"

You don't need to do anything if the if doesn't match so I don't see the point of using a ternary

Víctor
  • 3,029
  • 3
  • 28
  • 43
0

Don't use ternary side effects.

An if is easer to read

const el = document.getElementById("el");
if (el) el.hidden=true;
<div id="el">A</div>

Shorter for same result:

#el { display: none }
<div id="el">A</div>

Oneliner

document.querySelectorAll("#el").forEach(el => el.hidden=true);
<div id="el">A</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

This is the kind of thing Maybe is good for

const maybeSelect = selector => {
   const elem = document.querySelector(selector);
   return elem ? Just(elem) : Nothing();
};
maybeSelect('#el').effect(x => x.style.display = 'none');

A simplistic (awful) implementation

const Just = (value) => ({
   fold: (f = x => x) => f(value),
   map: f => Just(f(value)),
   effect: f => (f(value), Just(value))
})

const Nothing = () => ({
   fold: () => null,
   map: f => Nothing(),
   effect: f => Nothing()
})

Basically when you use effect on a Nothing, it does nothing, and whether you have a Nothing or a Just is decided in maybeSelect.

map allows you to transform the value and fold to retrieve it.

And of course you can chain effects and maps at will.

It may seem a bit overkill, but once you get used to it, it's addictive.

You can turn to libraries such as Folktale if you are interested.

geoffrey
  • 2,080
  • 9
  • 13
-2

Ok, I found a one-liner

[].filter.call([document.querySelector('#el')], el => el).forEach(el => el.style.display = "none");

Taken from here: https://stackoverflow.com/a/42532205/10684798

Dom
  • 645
  • 6
  • 17