【问题标题】:How to use querySelectorAll only for elements that have a specific attribute set?如何仅将 querySelectorAll 用于具有特定属性集的元素?
【发布时间】:2012-06-02 09:49:56
【问题描述】:

我正在尝试对所有设置了value 属性的复选框使用document.querySelectorAll

页面上还有其他复选框没有设置value,每个复选框的值都不一样。 id 和名称不是唯一的。

示例: <input type="checkbox" id="c2" name="c2" value="DE039230952"/>

如何只选择那些设置了值的复选框?

【问题讨论】:

  • 这包括空格吗?喜欢values=""
  • 其他复选框根本没有任何价值,因此不必包含它。

标签: javascript css-selectors selectors-api


【解决方案1】:

用你的例子:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

将示例中的 $$ 替换为 document.querySelectorAll:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

直接使用示例:

const $$ = document.querySelectorAll.bind(document);

一些补充:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

【讨论】:

    【解决方案2】:

    额外提示:

    多个“nots”,未隐藏且未禁用的输入:

    :not([type="hidden"]):not([disabled])
    

    你也知道你可以这样做:

    node.parentNode.querySelectorAll('div');
    

    这相当于 jQuery 的:

    $(node).parent().find('div');
    

    这将有效地递归地找到“节点”及以下的所有 div,HOT DAMN!

    【讨论】:

      【解决方案3】:

      你可以像这样使用querySelectorAll()

      var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');
      

      这转化为:

      获取属性为“value”且属性“value”不为空的所有输入。

      In this demo,它禁用具有非空白值的复选框。

      【讨论】:

      • 如何只选择复选框类型的输入?还有很多其他具有值属性的输入标签,但我只想要复选框。
      • @Soryn 添加[type="checkbox"]。更新了我的答案。
      • 很好的答案!这在很大程度上消除了在用于 DOM 遍历的迷你库中包含 jQuery 的需要。我在下面的答案中有一些额外的提示。
      • 你能告诉我这个语法是什么 input[value][type="checkbox"]:not([value=""] 我以前在javascript中没有看到这样的语法
      • @blackHawk 语法使用 CSS 选择器。正如MDN 所指定的,它“是一个包含一个或多个用逗号分隔的CSS 选择器的字符串”。你可以阅读 CSS 选择器here
      猜你喜欢
      • 2019-09-29
      • 1970-01-01
      • 2011-10-14
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      相关资源
      最近更新 更多