You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在DOM树中高效遍历两节点间节点:是否为已知命名问题?

遍历DOM树中两个节点间的所有节点

备选标题:遍历树中两个节点间的所有节点。

我有一棵DOM树(有序树,每层级的子元素有特定顺序)。已知树中的start和stop节点,且在深度优先遍历中start节点必然位于stop节点之前。我想要高效地查找/遍历这两个节点之间的所有节点,即若能确定某中间节点不包含stop节点,则无需递归遍历其所有后代。

这是否是一个知名(有命名的)问题?是否存在相关的遍历算法,例如通过计算共同祖先来决定是否遍历节点的后代?

示例0(同层级):

<body>
  <p>ignore this</p>
  <div id="start">start here</div>
  <p id="A">visit A</p>
  <p id="B">visit B</p>
  <p id="C">visit C <span>but <b>not</b> <i>all this</i></span></p>
  <div id="stop">stop here</div>
  <p>ignore this</p>
</body>

在示例0中,我希望按以下顺序访问节点:

  • #A
  • #B
  • #C(但不访问其所有后代)

示例1(stop节点层级更深):

<body>
  <p>ignore this</p>
  <div><h2><span id="start">start here</span> A1</h2> A2</div>
  <section id="B"><many><more><levels><of><content>…</many></section>
  <section id="C">
     <div id="D"><many><more><levels><of><content>…</many></div>
     <div id="E">
       <div id="F"><many><more><levels><of><content>…</many></div>
       <div id="stop">stop here</div>
       <p>ignore this</p>
     </div>
  </section>
  <p>ignore this</p>
</body>

在示例1中,我希望按以下顺序访问节点:

  • 文本节点A1和A2
  • #B(但不访问其所有后代)
  • #C(或许不需要?)
  • #D(但不访问其所有后代)
  • #E(或许不需要?)
  • #F(但不访问其所有后代)

示例2(stop节点层级更高):

<body>
  <p>ignore this</p>
  <div>
    <h2>
      <span id="start">start here</span>
      <div id="A">visit A</div>
      <section id="B"><many><more><levels><of><content>…</many></section>
    </h2>
    <section id="C"><many><more><levels><of><content>…</many></section>
  </div>
  <section id="D"><many><more><levels><of><content>…</many></section>
  <div id="stop">stop here</div>
  <p>ignore this</p>
</body>

在示例2中,我希望按以下顺序访问节点:

  • #A
  • #B(但不访问其后代)
  • #C(但不访问其后代)
  • #D(但不访问其后代)

内容的提问来源于stack exchange,提问作者Phrogz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 03:27:06