JavaScript报错setAttribute is not a function:批量设置元素required属性问题
问题:根据单选按钮状态批量为元素添加required属性
我想根据单选按钮的选中值,给数组里的每个元素批量添加/移除required属性。现在只能逐个设置,但批量操作不行,JavaScript不是我的强项,肯定哪里写错了。
我试过用forEach(function (item, i){item.setAttribute('required','true');}),但报错“item.setAttribute is not a function”。
原代码:
//assign required fields to variable const reqCollection = [document.getElementsByClassName("reqcheck")]; console.log(reqCollection); document.addEventListener('DOMContentLoaded', () => { // on .conditional_radio-wrapper click document.querySelectorAll('.conditional_radio-wrapper').forEach(trigger => { trigger.addEventListener('click', function () { //assign variable for "Are you a realtor?" let realtorRadio = document.querySelector('input[name="realtorChoice"]:checked').value; //log realtorRadio console.log(realtorRadio); //assign variable for "Are you represented by a realtor?" let repRadio = document.querySelector('input[name="realtorRep"]:checked').value; console.log(repRadio); //assign required fields to variable //if they are a realtor or represented by one if (realtorRadio == "Yes" || repRadio == "Yes") { reqCollection.forEach(function (item, i) { //does work item[0].setAttribute('required', 'true'); item[1].setAttribute('required', 'true'); item[2].setAttribute('required', 'true'); //doesn't work item.setAttribute('required', 'true'); }); } //else mark as not required else { reqCollection.forEach(function (item, i) { item[0].removeAttribute('required'); item[1].removeAttribute('required'); item[2].removeAttribute('required'); }); } }); }); });
问题分析
你犯了两个关键错误:
reqCollection定义错误:const reqCollection = [document.getElementsByClassName("reqcheck")];这里把document.getElementsByClassName返回的HTMLCollection(类数组对象)又套了一层数组,导致reqCollection是一个包含HTMLCollection的数组,遍历的时候item是整个集合而非单个元素,自然没有setAttribute方法。- HTMLCollection不能直接用数组的
forEach:getElementsByClassName返回的是类数组,不是真正的数组,直接用forEach会有问题,需要先转成数组。
修复后的代码
document.addEventListener('DOMContentLoaded', () => { // 获取所有需要设置的元素,转成真正的数组 const reqCollection = Array.from(document.getElementsByClassName("reqcheck")); // 给单选按钮容器绑定点击事件 document.querySelectorAll('.conditional_radio-wrapper').forEach(trigger => { trigger.addEventListener('click', function () { const realtorRadio = document.querySelector('input[name="realtorChoice"]:checked').value; const repRadio = document.querySelector('input[name="realtorRep"]:checked').value; // 统一判断是否需要添加required const needRequired = realtorRadio === "Yes" || repRadio === "Yes"; // 批量处理每个元素 reqCollection.forEach(item => { if (needRequired) { item.setAttribute('required', 'true'); } else { item.removeAttribute('required'); } }); }); }); });
关键修复点
- 用
Array.from()或者扩展运算符[...document.getElementsByClassName("reqcheck")]把HTMLCollection转成真正的数组,这样就能正常遍历每个元素。 - 把判断逻辑抽成
needRequired变量,简化代码结构。 - 遍历的时候每个
item就是单个DOM元素,直接调用setAttribute或removeAttribute即可,不用再通过索引逐个访问。
内容的提问来源于stack exchange,提问作者Patrick
相关产品推荐
相关产品推荐

