如何提取每个h2标签后紧随的第一个strong标签内容?
解决方法
别再把h2和strong分开存数组了,这种方式没法对应关联关系。正确的思路是逐个处理每个h2,从它之后的节点里递归查找第一个出现的strong标签,不管这个strong是直接在h2后面,还是嵌套在p这类标签里。
原生JavaScript实现代码
// 获取页面中所有h2元素 const h2List = document.querySelectorAll('h2'); const output = []; h2List.forEach(h2 => { // 先记录当前h2的文本内容 output.push(h2.textContent.trim()); // 从h2的下一个节点开始,递归查找第一个strong function findFirstStrong(node) { if (!node) return null; // 仅处理元素节点 if (node.nodeType === Node.ELEMENT_NODE) { // 当前节点就是strong,直接返回 if (node.tagName === 'STRONG') { return node; } // 遍历当前节点的子节点,查找嵌套的strong for (const child of node.children) { const found = findFirstStrong(child); if (found) return found; } } // 当前节点不是目标,继续找下一个兄弟节点 return findFirstStrong(node.nextSibling); } const firstStrong = findFirstStrong(h2.nextSibling); if (firstStrong) { output.push(firstStrong.textContent.trim()); } }); // 输出结果,格式符合需求 console.log(output.join('\n'));
jQuery简化实现
如果项目里已经引入jQuery,代码会更简洁:
const output = []; $('h2').each(function() { output.push($(this).text().trim()); // 查找当前h2之后所有节点里的第一个strong(包括后代节点) const targetStrong = $(this).nextAll().find('strong').first(); if (targetStrong.length) { output.push(targetStrong.text().trim()); } }); console.log(output.join('\n'));
逻辑说明
- 遍历每个h2,先收集它的文本
- 从h2的下一个兄弟节点开始,依次检查每个节点:
- 如果是strong标签,直接取它的文本
- 如果是其他元素节点(比如p),就深入到它的子节点里查找
- 直到找到第一个strong,或者遍历完所有后续节点
内容的提问来源于stack exchange,提问作者sofname
相关产品推荐
相关产品推荐

