jQuery如何选择两个指定元素之间的所有元素?
嘿,这个需求我之前也碰到过!要选中两个元素之间的所有兄弟节点,其实用原生JavaScript写个小函数就能轻松搞定,我给你两种方案,按需选就行~
解决方案:获取两个元素之间的所有兄弟元素
方案一:包含起始和结束元素的版本
如果你需要的是从#second到#fifth的全部元素(包括这两个节点本身),可以用这个函数:
function getElementsBetween(startSelector, endSelector) { // 获取起始和结束元素 const startEl = document.querySelector(startSelector); const endEl = document.querySelector(endSelector); // 边界检查:元素不存在或不在同一个父容器,返回空数组 if (!startEl || !endEl) return []; if (startEl.parentElement !== endEl.parentElement) return []; const elements = []; let currentEl = startEl; // 从起始元素开始遍历,直到遇到结束元素 while (currentEl) { elements.push(currentEl); if (currentEl === endEl) break; currentEl = currentEl.nextElementSibling; } return elements; } // 调用示例:获取#second到#fifth的所有元素 const result = getElementsBetween('#second', '#fifth'); console.log(result); // 输出包含#second、#third、#fourth、#fifth的数组
方案二:仅包含中间元素(不包括起始和结束)的版本
如果你的需求是起始元素之后、结束元素之前的元素(也就是排除#second和#fifth,只取中间的#third、#fourth),可以用这个调整后的版本:
function getElementsBetweenExclusive(startSelector, endSelector) { const startEl = document.querySelector(startSelector); const endEl = document.querySelector(endSelector); if (!startEl || !endEl) return []; if (startEl.parentElement !== endEl.parentElement) return []; const elements = []; let currentEl = startEl.nextElementSibling; // 从起始元素的下一个兄弟开始遍历,直到遇到结束元素停止 while (currentEl && currentEl !== endEl) { elements.push(currentEl); currentEl = currentEl.nextElementSibling; } return elements; } // 调用示例:获取#second之后、#fifth之前的元素 const result = getElementsBetweenExclusive('#second', '#fifth'); console.log(result); // 输出包含#third、#fourth的数组
注意事项
这两个函数都依赖一个前提:起始元素和结束元素必须是同一个父元素下的兄弟节点。如果它们不在同一个父容器里,函数会直接返回空数组,你可以根据自己的实际DOM结构,再调整边界判断的逻辑哦~
内容的提问来源于stack exchange,提问作者Kacper G.
相关产品推荐
相关产品推荐

