Javascript 缩短查询选择器和样式更改

Javascript 缩短查询选择器和样式更改,javascript,selectors-api,Javascript,Selectors Api,有没有办法缩短querySelector结果并对其结果执行操作?最好是一行 想象一下有一个元素: A 和相应的JavaScript代码: const el = document.querySelector("#el"); el ? el.style.display = "none" : null; 假设divel可能在页面上呈现,也可能不在页面上呈现,因此使用三元运算符,有没有办法将上述逻辑缩短为一行?好的,我找到了一行 [].filter.call(

有没有办法缩短querySelector结果并对其结果执行操作?最好是一行

想象一下有一个元素:

A

和相应的JavaScript代码:

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

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

假设divel可能在页面上呈现,也可能不在页面上呈现,因此使用三元运算符,有没有办法将上述逻辑缩短为一行?

好的,我找到了一行

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

摘自这里: 为什么不

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

如果if不匹配,你不需要做任何事情,所以我不认为使用三元的意义。不要使用三元的副作用

if更容易阅读

const el=document.getElementByIdel; 如果el.hidden=真; A这是一种可能对你有益的事情

const maybeSelect = selector => {
   const elem = document.querySelector(selector);
   return elem ? Just(elem) : Nothing();
};
过于简单的可怕的实现

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()
})
基本上,当你在一个“无”上使用效果时,它什么也不起作用,而你是“无”还是“公正”则由maybeSelect决定

映射允许您变换值并折叠以检索它

当然,你可以随意链接效果和贴图

这似乎有点过分,但一旦你习惯了,它就会上瘾


如果您感兴趣,可以使用库。

我认为唯一的方法是不要创建const并直接在短代码中使用它。如果您需要const,您的方法已经是您可以执行的最佳方法document.querySelectorel?.style.setPropertydisplay,无。但是为什么首先要缩短代码?这开始进入黑客的领域;您的92A querySelector只返回一个项,所以您不能迭代,也许这个解决方案适合querySelectorAll,它返回一个array@Del它被包装在数组中?@Del任何投票否决我的CSS的人都应该再次查看
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()
})