获取页面所有复选框

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

问题

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

解答

方法一:querySelectorAll

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

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

方法二:getElementsByTagName + 过滤

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

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

方法三:getElementsByName

// 如果 checkbox 有相同的 name 属性
const checkboxes = document.getElementsByName('hobby');

获取选中的 checkbox

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

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

完整示例

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

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

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

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

关键点

  • querySelectorAll 是最简洁的方式,支持 CSS 选择器语法
  • querySelectorAll 返回静态 NodeList,getElementsByTagName 返回动态 HTMLCollection
  • 使用 :checked 伪类可以直接筛选选中状态的 checkbox
  • NodeList 需要转换为数组才能使用 mapfilter 等方法
  • type 属性比较时不区分大小写,checkboxCHECKBOX 都能匹配