jQuery 同胞
核对水平遍历同级元素的七个方法 siblings()、next()、nextAll()、nextUntil() 与 prev()、prevAll()、prevUntil() 的方向、边界及过滤行为。
学完这一章,你能够
- 核对水平遍历同级元素的七个方法 siblings()、next()、nextAll()、nextUntil() 与 prev()、prevAll()、prevUntil() 的方向、边界及过滤行为。
水平遍历 DOM 树的七个方法概览
同胞(Siblings)指共享同一个直接父元素的平级节点。jQuery 为水平遍历提供 7 个方法:双向全同胞 `siblings()`、向后移动的 `next()` / `nextAll()` / `nextUntil()`,以及向前移动的 `prev()` / `prevAll()` / `prevUntil()`。
siblings():查找全部或指定类型的同胞元素
`siblings()` 返回被选元素在同父容器内的所有其他同级元素,且不包含被选元素自身。本站离线 Chromium 在含 9 个同级子节点的 `#sib-box`(`p#p-before`、`span#sp-before`、`h2#anchor-h2`、`h3#h3-el`、`p#p-after`、`h4#h4-el`、`h5#h5-el`、`h6#h6-el`、`p#p-tail`)上实测:`$('h2').siblings()` 返回其余 8 个节点且明确不包含 `h2#anchor-h2`。
为 `siblings()` 传入可选选择器即可按条件过滤同胞。本站实测 `$('h2').siblings('p')` 仅返回前后 3 个段落同胞 `['p#p-before', 'p#p-after', 'p#p-tail']`,将 `p#p-after` 置红(`rgb(255, 0, 0)`),而相邻的 `h3#h3-el` 保持浅灰(`rgb(211, 211, 211)`)。
向后遍历:next()、nextAll() 与 nextUntil()
`next()` 仅返回紧邻被选元素之后的下一个同胞元素,单元素调用最多返回 1 项。本站实测 `$('h2').next()` 返回 `['h3#h3-el']`(长度为 1),而对最后一个同胞 `#p-tail` 调用 `.next()` 则返回空列表 `[]`。
`nextAll()` 返回位于被选元素之后的全部同胞元素。本站实测 `$('h2').nextAll()` 依次返回 6 个后续同胞 `['h3#h3-el', 'p#p-after', 'h4#h4-el', 'h5#h5-el', 'h6#h6-el', 'p#p-tail']`。
`nextUntil(stopSelector[, filterSelector])` 返回介于当前元素与首个匹配停止条件的后续同胞之间的全部元素,同样不包含两端边界。本站实测 `$('h2').nextUntil('h6')` 返回 `['h3#h3-el', 'p#p-after', 'h4#h4-el', 'h5#h5-el']`;再叠加过滤参数 `'p'` 则只保留 `['p#p-after']`。
向前遍历:prev()、prevAll() 与 prevUntil()
`prev()`、`prevAll()` 与 `prevUntil()` 的用法与 `next` 系列完全对称,区别在于沿着 DOM 树向前检索位于当前元素之前的同胞节点。本站实测:`$('h2').prev()` 返回 `['span#sp-before']`;`$('h2').prevAll()` 按由近及远顺序返回 `['span#sp-before', 'p#p-before']`;`$('#h6-el').prevUntil('h2')` 反向收集介于 `h6` 与 `h2` 之间的 4 个节点 `['h5#h5-el', 'h4#h4-el', 'p#p-after', 'h3#h3-el']`;首个节点 `#p-before` 调用 `.prev()` 返回 `[]`。
在离线 Chromium 中全量实测 siblings() 及 next/prev 全套六种水平遍历方法
展开查看收起
"""Offline Playwright Chromium lab for jQuery Chapter 24 (traversing-siblings)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Siblings Lab</title>
<style>
.siblings * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 8px; }
</style>
</head>
<body class="siblings">
<div id="sib-box">div (父元素)
<p id="p-before">p (前同胞)</p>
<span id="sp-before">span (前同胞)</span>
<h2 id="anchor-h2">h2 (当前元素)</h2>
<h3 id="h3-el">h3</h3>
<p id="p-after">p (后同胞)</p>
<h4 id="h4-el">h4</h4>
<h5 id="h5-el">h5</h5>
<h6 id="h6-el">h6</h6>
<p id="p-tail">p (末尾同胞)</p>
</div>
<script>
(function (global) {
function unique(arr) {
const out = [];
for (const el of arr) {
if (el && el.nodeType === 1 && !out.includes(el)) out.push(el);
}
return out;
}
function wrap(nodes) {
const list = unique(nodes);
return {
nodes: list,
length: list.length,
ids() {
return list.map(el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
},
css(props) {
for (const el of list) {
for (const [k, v] of Object.entries(props)) el.style[k] = v;
}
return this;
},
siblings(sel) {
const res = [];
for (const el of list) {
if (!el.parentElement) continue;
for (const ch of Array.from(el.parentElement.children)) {
if (ch !== el && (!sel || ch.matches(sel))) res.push(ch);
}
}
return wrap(res);
},
next(sel) {
const res = [];
for (const el of list) {
const n = el.nextElementSibling;
if (n && (!sel || n.matches(sel))) res.push(n);
}
return wrap(res);
},
nextAll(sel) {
const res = [];
for (const el of list) {
let cur = el.nextElementSibling;
while (cur) {
if (!sel || cur.matches(sel)) res.push(cur);
cur = cur.nextElementSibling;
}
}
return wrap(res);
},
nextUntil(stopSel, filterSel) {
const res = [];
for (const el of list) {
let cur = el.nextElementSibling;
while (cur) {
if (stopSel && cur.matches(stopSel)) break;
if (!filterSel || cur.matches(filterSel)) res.push(cur);
cur = cur.nextElementSibling;
}
}
return wrap(res);
},
prev(sel) {
const res = [];
for (const el of list) {
const p = el.previousElementSibling;
if (p && (!sel || p.matches(sel))) res.push(p);
}
return wrap(res);
},
prevAll(sel) {
const res = [];
for (const el of list) {
let cur = el.previousElementSibling;
while (cur) {
if (!sel || cur.matches(sel)) res.push(cur);
cur = cur.previousElementSibling;
}
}
return wrap(res);
},
prevUntil(stopSel, filterSel) {
const res = [];
for (const el of list) {
let cur = el.previousElementSibling;
while (cur) {
if (stopSel && cur.matches(stopSel)) break;
if (!filterSel || cur.matches(filterSel)) res.push(cur);
cur = cur.previousElementSibling;
}
}
return wrap(res);
}
};
}
global.$ = function (arg) {
if (arg === document) return { ready(fn) { fn(); } };
if (typeof arg === 'string') return wrap(Array.from(document.querySelectorAll(arg)));
return wrap([]);
};
})(window);
</script>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page(viewport={"width": 1000, "height": 700})
page.set_content(HTML_DOC)
c1 = page.evaluate("""() => {
const res = $("h2").siblings();
return {
all_siblings: res.ids(),
count: res.length,
excludes_self: !res.ids().includes("h2#anchor-h2")
};
}""")
exp1 = {
"all_siblings": [
"p#p-before", "span#sp-before", "h3#h3-el", "p#p-after",
"h4#h4-el", "h5#h5-el", "h6#h6-el", "p#p-tail",
],
"count": 8,
"excludes_self": True,
}
cases.append({"name": "siblings_all_excluding_self", "passed": c1 == exp1, "expected": exp1, "actual": c1})
c2 = page.evaluate("""() => {
const res = $("h2").siblings("p").css({ color: "red", border: "2px solid red" });
return {
p_siblings: res.ids(),
p_after_color: getComputedStyle(document.getElementById("p-after")).color,
h3_color: getComputedStyle(document.getElementById("h3-el")).color
};
}""")
exp2 = {
"p_siblings": ["p#p-before", "p#p-after", "p#p-tail"],
"p_after_color": "rgb(255, 0, 0)",
"h3_color": "rgb(211, 211, 211)",
}
cases.append({"name": "siblings_filtered_by_selector", "passed": c2 == exp2, "expected": exp2, "actual": c2})
c3 = page.evaluate("""() => ({
h2_next: $("h2").next().ids(),
h2_next_count: $("h2").next().length,
tail_next: $("#p-tail").next().ids()
})""")
exp3 = {
"h2_next": ["h3#h3-el"],
"h2_next_count": 1,
"tail_next": [],
}
cases.append({"name": "next_single_immediate_sibling", "passed": c3 == exp3, "expected": exp3, "actual": c3})
c4 = page.evaluate("""() => ({
h2_next_all: $("h2").nextAll().ids(),
h2_next_until_h6: $("h2").nextUntil("h6").ids(),
h2_next_until_h6_only_p: $("h2").nextUntil("h6", "p").ids()
})""")
exp4 = {
"h2_next_all": ["h3#h3-el", "p#p-after", "h4#h4-el", "h5#h5-el", "h6#h6-el", "p#p-tail"],
"h2_next_until_h6": ["h3#h3-el", "p#p-after", "h4#h4-el", "h5#h5-el"],
"h2_next_until_h6_only_p": ["p#p-after"],
}
cases.append({"name": "next_all_and_next_until", "passed": c4 == exp4, "expected": exp4, "actual": c4})
c5 = page.evaluate("""() => ({
h2_prev: $("h2").prev().ids(),
h2_prev_all: $("h2").prevAll().ids(),
h6_prev_until_h2: $("#h6-el").prevUntil("h2").ids(),
p_before_prev: $("#p-before").prev().ids()
})""")
exp5 = {
"h2_prev": ["span#sp-before"],
"h2_prev_all": ["span#sp-before", "p#p-before"],
"h6_prev_until_h2": ["h5#h5-el", "h4#h4-el", "p#p-after", "h3#h3-el"],
"p_before_prev": [],
}
cases.append({"name": "prev_prev_all_and_prev_until", "passed": c5 == exp5, "expected": exp5, "actual": c5})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
对同一父容器下的某个节点,prevAll() 与 nextAll() 互不相交且并集恰为 siblings()(均不含自身);nextUntil('h6') 在遇到首个 h6 时停止,不会包含起止两端的任何边界元素。