ShuffleJS搜索功能报Cannot read property 'textContent' of null错误
ShuffleJS 搜索功能报错解决方案
问题描述
- 正在学习ShuffleJS用于项目开发,其搜索功能 运行异常
- 触发报错:输入搜索条目时,持续抛出
Cannot read property 'textContent' of null错误 - 初始参考官方高级过滤文档的代码编写逻辑,但无法正常运行
现有代码
HTML 结构
<section class="search"> <div class="container"> <div class="row"> <div class="col-12"> <div class="form-group"> <input type="search" id="search" class="form-control"> </div> </div> </div> </div> </section> <section> <div class="container"> <div class="row" id="grid"> <div class="box green" data-groups='["green"]' data-title="blue">green</div> <div class="box red" data-groups='["red"]' data-title="red">red</div> <div class="box green" data-groups='["green"]' data-title="blue">green</div> <div class="box red" data-groups='["red"]' data-title="red">red</div> <div class="box green" data-groups='["green"]' data-title="blue">green</div> <div class="box red" data-groups='["red"]' data-title="red">red</div> <div class="col-md-2 my-sizer"></div> </div> </div> </section>
原有 JavaScript 逻辑
const Shuffle = window.Shuffle; const element = $('#grid'); const sizer = $('.my-sizer'); const shuffle = new Shuffle(element, { itemSelector: '.box', sizer }) $('#search').on('keyup', (e) => { var searchText = e.target.value.toLowerCase(); shuffle.filter((element, shuffle) => { var titleElement = element.querySelector('.box'); // 错误抛出位置 var titleText = titleElement.textContent.toLowerCase().trim(); return titleText.indexOf(searchText) !== -1; }); })
问题根源
shuffle.filter()回调函数的第一个入参element,本身就是匹配初始化时配置的itemSelector的DOM节点,也就是这里的每一个.box元素- 原有代码在这个已经是
.box的节点上,再执行element.querySelector('.box')查找内部的子级.box元素,自然找不到匹配节点,返回null,读取null的textContent属性就会抛出指定错误 - 即使参考官方示例复现,只要DOM结构里没有在
.box内部嵌套另一层.box子元素,这个错误就必然触发
修复方案
直接利用filter回调返回的节点本身做文本匹配,不需要重复查询子元素,优化后的代码如下:
$('#search').on('keyup', (e) => { const searchText = e.target.value.toLowerCase().trim(); shuffle.filter((element) => { // 直接读取节点上自定义的data-title属性做匹配 const titleText = element.dataset.title.toLowerCase().trim(); // 使用includes方法判断匹配逻辑,比indexOf写法更简洁 return titleText.includes(searchText); }); });
补充说明
- 如果需要匹配元素的可见文本而不是自定义属性,可以直接读取当前节点的
textContent,因为element本身就是.box节点,无需嵌套查询 - 初始化Shuffle实例时,要确保DOM节点完全渲染完成,避免因为加载时序问题导致选择器匹配不到节点
- 现有代码里的sizer元素属于Shuffle的测量节点,不要被后续的过滤逻辑影响匹配范围
内容的提问来源于stack exchange,提问作者Student22
相关产品推荐
相关产品推荐

