JS如何从指定class元素中仅筛选li标签内容复制到另一class元素?
解决方案
核心实现逻辑
- 选中
CardData下所有<li>元素,不需要手动指定索引,可自适应任意数量的列表项 - 将筛选出的
<li>元素统一放入新的<ul>容器中,保留列表默认的项目符号样式 - 仅将筛选后的列表内容写入
optionData,自动过滤<a>、<button>等不需要的元素
修改后的JS代码
function details(saad) { // 获取当前卡片对应的CardData元素 const cardData = saad.parentElement.querySelector('.CardData'); // 选中CardData下所有li元素 const allLi = cardData.querySelectorAll('li'); // 创建临时ul容器,保证li的列表样式正常显示 const tempUl = document.createElement('ul'); // 遍历所有li,克隆后添加到临时ul中 allLi.forEach(liItem => { tempUl.appendChild(liItem.cloneNode(true)); }); // 将处理好的列表内容写入optionData document.querySelector('.optionData').innerHTML = tempUl.innerHTML; } // 注意:原有代码同时在HTML里写了onclick绑定,又做了全局遍历绑定,会导致函数重复执行,建议保留其中一种即可 // 如果要保留这行全局绑定,就删掉HTML中button标签里的 onclick="details(this)" 属性 document.querySelectorAll(".CardBtn").forEach(btn => { btn.addEventListener('click', function() { details(this); }); });
优化说明
- 不需要手动指定列表索引,无论
<li>数量多少都能自动全部复制 - 临时
<ul>容器保证了列表项默认的项目符号可以正常显示,不需要额外加CSS - 自动过滤
<a>、<button>等非<li>元素,符合需求
内容的提问来源于stack exchange,提问作者user16716458
相关产品推荐
相关产品推荐

