类型‘NodeListOf<Element>’无‘remove’属性,如何移除指定类名元素?
解决“NodeListOf不存在‘remove’属性”的错误
你遇到的问题核心在于:document.querySelectorAll()返回的是NodeList元素集合,这个集合本身没有remove()方法,只有单个DOM元素才支持该方法,直接调用集合的remove()自然会报错。
另外你的代码里还有两处小问题:
getAttribute()直接返回属性值,不需要额外加.value,否则会得到undefinedforEach的语法有误,缺少箭头函数的=>
以下是修正后的完整代码:
const questionKey = SelectElement.getAttribute("data-key"); const currentQuestionId = SelectElement.getAttribute("data-current-question"); const questionData = getCategoryQuestionsByProfile?.data?.questionOptionsList.filter( (d) => Number(hierarchyQuestionId) === Number(d.id) ); const bqCounter = document.querySelectorAll(".bq-counter"); bqCounter.forEach((e, index) => { if (index + 1 > questionLevel) { // 获取所有目标元素的集合 const targetElems = document.querySelectorAll(`.bq_detect_${questionKey}_${index + 1}`); // 遍历集合,逐个移除每个元素 targetElems.forEach(elem => elem.remove()); } });
兼容补充:
如果需要适配不支持NodeList.forEach的旧浏览器(比如IE),可以把集合转成数组再遍历:
// 转成数组后遍历 Array.from(targetElems).forEach(elem => elem.remove());
或者用传统for循环:
for (let i = 0; i < targetElems.length; i++) { targetElems[i].remove(); }
内容的提问来源于stack exchange,提问作者Alish Madhukar
相关产品推荐
相关产品推荐

