获取页面所有复选框

使用 DOM API 获取页面中所有 checkbox 元素的几种方法

问题

如何获取页面中所有的 checkbox 元素?

解答

方法一:querySelectorAll(推荐)

// 使用属性选择器获取所有 type="checkbox" 的 input
const checkboxes = document.querySelectorAll('input[type="checkbox"]');

// 返回 NodeList,可以直接遍历
checkboxes.forEach(checkbox => {
  console.log(checkbox.name, checkbox.checked);
});

方法二:getElementsByTagName + 过滤

// 获取所有 input 元素
const inputs = document.getElementsByTagName('input');

// 过滤出 checkbox
const checkboxes = Array.from(inputs).filter(input => input.type === 'checkbox');

方法三:getElementsByName(适用于同名复选框组)

// 获取特定 name 的复选框组
const checkboxes = document.getElementsByName('hobby');

获取选中的复选框

// 只获取被选中的 checkbox
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]:checked');

// 获取选中项的值
const values = Array.from(checkedBoxes).map(cb => cb.value);

完整示例

<form id="myForm">
  <input type="checkbox" name="fruit" value="apple"> 苹果
  <input type="checkbox" name="fruit" value="banana" checked> 香蕉
  <input type="checkbox" name="fruit" value="orange"> 橙子
</form>

<script>
// 获取所有复选框
const all = document.querySelectorAll('#myForm input[type="checkbox"]');
console.log('总数:', all.length); // 3

// 获取选中的
const checked = document.querySelectorAll('#myForm input[type="checkbox"]:checked');
console.log('选中:', checked.length); // 1

// 获取选中的值
const values = [...checked].map(cb => cb.value);
console.log('选中的值:', values); // ['banana']
</script>

关键点

  • querySelectorAll('input[type="checkbox"]') 是最简洁的方式
  • 使用 :checked 伪类可以只获取选中的复选框
  • querySelectorAll 返回静态 NodeList,getElementsByTagName 返回动态 HTMLCollection
  • NodeList 可以直接用 forEach,HTMLCollection 需要先转数组
  • 限定范围时可以加上父元素选择器,如 #form input[type="checkbox"]