多个class为question的div如何用JS选中指定节点并添加q6类div
解决方法
完全可以实现,以下是3种常用的实现方案,适配不同的场景:
方案1:使用CSS伪类:nth-child直接选中(最简洁,依赖元素顺序)
所有.question都是#content的直接子元素,第6个元素对应伪类参数为6(注意:nth-child计数从1开始),直接用选择器命中即可:
// 选中第6个question节点 const q6Container = document.querySelector('#content .question:nth-child(6)'); // 创建需要插入的div const q6Div = document.createElement('div'); q6Div.className = 'q6'; // 插入到容器末尾(刚好对应注释要求的位置) q6Container.appendChild(q6Div);
方案2:通过索引选取(和方案1逻辑类似,更直观)
先获取所有.question节点组成的集合,取下标为5的节点即可(注意JS类数组下标从0开始,第6个元素对应下标5):
const allQuestions = document.querySelectorAll('.question'); const q6Container = allQuestions[5]; // 后续创建插入节点的代码和方案1一致 const q6Div = document.createElement('div'); q6Div.className = 'q6'; q6Container.appendChild(q6Div);
方案3:通过文本内容匹配选取(最稳妥,不依赖元素顺序)
如果后续题目顺序可能调整,推荐通过匹配Question 6的文本定位节点,不会因为顺序变化选错:
const allQuestions = document.querySelectorAll('.question'); let q6Container; // 遍历所有题目匹配标题内容 for (const q of allQuestions) { const h2Text = q.querySelector('h2')?.textContent || ''; if (h2Text.includes('Question 6')) { q6Container = q; break; } } // 插入节点 if (q6Container) { const q6Div = document.createElement('div'); q6Div.className = 'q6'; q6Container.appendChild(q6Div); }
内容的提问来源于stack exchange,提问作者Cats'BBT
相关产品推荐
相关产品推荐

