如何通过 ID 将一组引用项的顺序与其相关元素节点在 DOM 树中的优先级同步?

How does one synchronize the order of an array of reference-items with the precedence of their related element-nodes within the DOM tree by their IDs?

如何通过知道元素在 DOM

中的位置来对元素 id 进行排序

我在页面上有一个元素 ID 数组,但该数组未按它们在 DOM/page 中的位置排序。 我想按它们在页面上的位置对它们进行排序。

数组:

[{ id:'first', type:'TEXT'},{id:'third',type:'DROPDOWN'},{id:'second',type:'TEXT'}]

输出:

[{id:'first', type:'TEXT'},{id:'second',type:'TEXT'},{id:'third',type:'DROPDOWN'}]

适用于任何 DOM 结构的通用方法遵循以下步骤...

  1. 为引用项的无序数组中列出的任何引用创建基于引用-id 的查找-table/地图/索引。使用 reduce 完成此任务。
  2. 检索从自己选择​​的根节点开始的所有元素节点的数组,例如使用getElementsByTagName('*').
  3. filter the element-array by existing reference-ids while using the reference-lookup as the filter-function's this context.
  4. map the filtered element array of step 3 back to an array of reference-items by each element's id while using again the reference-lookup as the map-function's this context;从而通过将此顺序映射到最终结果来保留前者的顺序。

...并且可能看起来类似于下一个提供的示例代码...

const unorderedReferenceList = [
  { id: 'bar', type: 'TEXT' },
  { id: 'baz', type: 'DROPDOWN' },
  { id: 'foo', type: 'TEXT' },
];
console.log({ unorderedReferenceList });

const referenceIndex = unorderedReferenceList
  .reduce((index, reference) => {
    index[reference.id] = reference;
    return index;
  }, {});

console.log({ referenceIndex });

const elementList = Array.from(
  document.body.getElementsByTagName('div')
);
console.log({ elementList });

const filteredElementList = elementList
  .filter(function (elm) {
    return (elm.id in this);
  }, referenceIndex);

console.log({ filteredElementList });

const orderedReferenceList = filteredElementList
  .map(function (elm) {
    return this[elm.id];
  }, referenceIndex);

console.log({ orderedReferenceList });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<div>
  <div>

    <div>
      <div>
        <div></div>
        <div id="foo">foo</div>
      </div>
      <div id="bar">bar</div>
    </div>
    
  </div>
  <div>

    <div>
      <div id="baz">baz</div>
      <div></div>
    </div>

  </div>
</div>