如何获取NodeList内部元素,解决调用getElementById不存在报错问题
错误原因与修复方案
1. 方法调用错误
getElementById 是仅挂载在 document 对象下的方法,普通 DOM 元素实例没有该方法,所以你在单个 .row 元素上调用 getElementById 会抛出未定义错误。可以使用元素自身的 querySelector 方法查找当前元素下的后代节点。
2. 空值判断错误
previousElementSibling 和 nextElementSibling 在没有对应兄弟节点时返回的是 null 原始值,你和字符串 'null' 做全等判断永远为假,逻辑不会生效,直接和 null 比对即可。
3. 按钮选择逻辑错误
你在处理下移按钮的 else 分支中,错误选中了上移按钮,导致下移按钮的激活状态永远不会被正确设置。
4. HTML ID 重复问题
ID 属性在整个 HTML 文档中必须唯一,你当前所有行的上移、下移按钮都用了相同 ID,属于不规范写法,也会影响元素选择。建议把按钮的 ID 改为类名:
<button type="button" class="btn-custom mx-0 move-down-btn"> <i class="fas fa-arrow-down"></i> </button> <button type="button" class="btn-custom mx-0 move-up-btn"> <i class="fas fa-arrow-up"></i> </button>
修正后完整代码
function checkMoveButtons(){ // 注意原HTML容器ID是大写List,选择器要对应,也可以把HTML的ID改为小写list保持统一 const unitsRows = document.querySelectorAll("#List .row"); for (let i = 0; i < unitsRows.length; i++) { const currentRow = unitsRows[i]; const listUnitAbove = currentRow.previousElementSibling; const listUnitBelow = currentRow.nextElementSibling; // 查找当前行内的上下按钮 const moveUpBtn = currentRow.querySelector('.move-up-btn'); const moveDownBtn = currentRow.querySelector('.move-down-btn'); // 处理上移按钮 if (listUnitAbove === null){ moveUpBtn.classList.add('btn-deactivate'); moveUpBtn.disabled = true; } else { moveUpBtn.classList.remove('btn-deactivate'); moveUpBtn.disabled = false; } // 处理下移按钮 if (listUnitBelow === null){ moveDownBtn.classList.add('btn-deactivate'); moveDownBtn.disabled = true; } else { moveDownBtn.classList.remove('btn-deactivate'); moveDownBtn.disabled = false; } } }
内容的提问来源于stack exchange,提问作者Artemis
相关产品推荐
相关产品推荐

