JavaScript自定义元素选择器运行异常排查及优化方案求助
问题排查
document.querySelectorAll()遵循CSS选择器语法,匹配类名需要加.前缀,匹配ID需要加#前缀,你传入的参数没有加对应前缀,导致无法匹配到目标元素,返回空数组- 你封装的
getElement返回的是所有匹配元素组成的数组,获取ID对应元素时直接对数组调用.innerText属性会报错,需要先取下标[0]获取到真实DOM元素再操作
原始代码修复版
const getElement = (el) => { return [...document.querySelectorAll(el)] }; // 类选择器补充.前缀 let divWithClass = getElement('.my-class'); console.log('div with class', divWithClass[0].innerText); // ID选择器补充#前缀,取下标0获取DOM元素 let divWithId = getElement('#my-id'); console.log('div with id', divWithId[0].innerText);
对应的HTML代码无需修改。
优化封装方案
可以兼顾单元素/多元素选择、支持指定父级查找范围,适配更多使用场景,用法和常用的jQuery选择器对齐,学习成本低:
/** * 自定义元素选择器 * @param {string} selector CSS选择器 * @param {HTMLElement} [parent=document] 查找范围的父元素,默认为整个文档 * @returns {HTMLElement|Array<HTMLElement>} ID选择器返回单个元素,其余返回匹配元素数组 */ const $ = (selector, parent = document) => { // ID选择器直接返回单个元素 if (selector.startsWith('#')) { return parent.querySelector(selector) } // 其他选择器返回元素数组 return [...parent.querySelectorAll(selector)] } // 使用示例 // 查找类名元素,返回数组 const classEls = $('.my-class') console.log(classEls[0].innerText) // 查找ID元素,直接返回单个DOM const idEl = $('#my-id') console.log(idEl.innerText) // 从指定父元素内查找子元素 const childEls = $('.child-class', idEl)
内容的提问来源于stack exchange,提问作者user16290953
相关产品推荐
相关产品推荐

