如何仅对具有特定属性集的元素使用 querySelectorAll?

2022-08-30 02:01:51

我正在尝试用于设置了该属性的所有复选框。document.querySelectorAllvalue

页面上还有其他未设置的复选框,每个复选框的值都不同。但是,ID和名称不是唯一的。value

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

如何仅选中设置了值的复选框?


答案 1

你可以像这样使用:querySelectorAll()

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

这意味着:

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

在此演示中,它将禁用具有非空值的复选框。


答案 2

以您的示例为例:

<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 $()