javascript - 如何使用 Javascript 有效地确定 HTML 文档中同级元素的相对顺序

标签 javascript html performance dom

简单地说,我需要确定两个兄弟元素中哪一个在 DOM 顺序中排在第一位,但它们可能不是直接相邻的兄弟元素。我当前用于执行此操作的代码如下所示:

/**
 * Determine if an element comes before or after another element.
 *
 * This requires both elements to be siblings.
 *
 * @param {Element} el1 - The element to use as a reference.
 * @param {Element} el2 - The element to look for.
 * @returns {?boolean} True if el2 comes before el1, false if el1 comes before el2, undefined otherwise.
 */
function isBefore(el1, el2) {
    let tmp = el1

    while (tmp.previousElementSibling) {
        if (tmp.previousElementSibling === el2) {
            return true
        }

        tmp = tmp.previousElementSibling
    }

    tmp = el1.nextElementSibling

    while (tmp.nextElementSibling) {
        if (tmp.nextElementSibling === el2) {
            return false
        }

        tmp = tmp.nextElementSibling
    }

    return undefined
}

我想知道是否有一些更有效的方法可以在普通 JavaScript 中执行此检查。

最佳答案

您可以使用 contains(...) 来执行此操作当你的 sibling 用完时就升一级,这是一个例子:

function isBefore(el1, el2) {
    if (el1.contains(el2) || el2.contains(el1)) {
        return undefined; // not before or after, it's a parent child relationship.
    }

    let tmp = el1.previousElementSibling || el1.parentElement

    while (tmp) {
        if (tmp === el2 || tmp.contains(el2)) {
            return true
        }
        tmp = tmp.previousElementSibling || tmp.parentElement;
    }

    return false; // if it is not before, it must be after.
}

关于javascript - 如何使用 Javascript 有效地确定 HTML 文档中同级元素的相对顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57379579/

相关文章:

python - 用于处理大整数的多个数字数组

javascript - 从 Javascript 函数获取字符串

javascript - 使用SheetJS将动态创建的表格内容保存在excel文件中

jquery mouseover如何使用获取当前隐藏值

Python:与 MacOS 相比,Scipy 在 Windows10 上非常慢

python - 优化 numpy 数组乘法 : * faster than numpy. 点?

javascript - 如何计算所见即所得编辑器javascript中的单词数?

javascript - ng2-charts 如何获取多次推送的结果?

javascript - JS Contenteditable 下划线不起作用

html - 如何用CSS和HTML实现如下导航