【问题标题】:Exclude specific element by id on querySelectorAll在 querySelectorAll 上按 id 排除特定元素
【发布时间】:2018-06-11 23:01:00
【问题描述】:

我尝试从以下位置获取数组的长度:

document.querySelectorAll('select,input,textarea');
alert(Object.keys(arr).length);//19

在该数组中,我必须排除 4 个元素,即 2 个 input type="hidden",以及 2 个带有特定 id's 的元素,所以我尝试使用 :not selector

document.querySelectorAll('select,input,textarea,input:not[type="hidden",input:not[id="input_up_img_perfil"],input:not[id="sub_img_perfil"],');
alert(Object.keys(arr).length);//19

该查询的正确语法是什么?

【问题讨论】:

  • input:not('[type=hidden]'),您缺少否定运算符(:not())的括号,以及应该出现在第一个 "hidden" 之后的结束 ] 字符。跨度>
  • 欢迎否定,如果可能,请尝试任何提示以使该问题变得更好!

标签: javascript css-selectors


【解决方案1】:

试试这个:

document.querySelectorAll('select,input:not([type="hidden"]):not(#input_up_img_perfil):not(#sub_img_perfil),textarea');

它应该工作得很好;)

其实很简单:首先,你需要给:not 操作符加上括号。然后,您需要考虑正确的 CSS 查询来选择您需要的内容。

不起作用的示例:

'input:not([type="hidden"]),input:not(#input_up_img_perfil),input:not(#sub_img_perfil)'

因为您实际上有三个查询并且结果将在最后合并,因为input:not(#input_up_img_perfil) 对隐藏字段没有限制,即使您设置了input:not([type="hidden"]),您也会在结果中获得它们。

这就是为什么您需要执行以下操作:

'input:not([type="hidden"]):not(#input_up_img_perfil):not(#sub_img_perfil)'

这里,输入标签只有一个查询,有三个约束!

希望这很清楚;)

【讨论】:

  • 完美,tkssss!
  • 谢谢! (删除原始评论,因为这将很快。)
【解决方案2】:

举例

<input class="test">
<input class="test asd">

试试这样的:

document.querySelectorAll('span.test:not(.asd)');

代替:

document.querySelectorAll('select,input,textarea,input:not[type="hidden",input:not[id="input_up_img_perfil"],input:not[id="sub_img_perfil"],');

【讨论】:

    【解决方案3】:

    您可以将节点集合转换为数组,然后使用Array#filter 过滤掉不需要的元素:

    Array.from(document.querySelectorAll('select,input,textarea'))
      .filter(item => item.type !== 'hidden' || item.id !== 'input_up_img_perfil' || item.id !== 'sub_img_perfil');
    

    【讨论】:

    • 请注意,我需要使用exclude element with :not selector 方式,你知道吗?
    猜你喜欢
    • 2018-06-16
    • 1970-01-01
    • 2016-10-16
    • 2019-12-16
    • 2021-05-20
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多