最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I test which node comes first? - Stack Overflow

programmeradmin0浏览0评论

I have two given nodes that are stored inside variables. Is there a simple, low resource usage, solution to find which node es first in the document? Both nodes should be siblings but may be many nodes apart.

I have two given nodes that are stored inside variables. Is there a simple, low resource usage, solution to find which node es first in the document? Both nodes should be siblings but may be many nodes apart.

Share Improve this question edited Dec 21, 2015 at 23:16 www139 asked Dec 21, 2015 at 23:06 www139www139 5,2473 gold badges38 silver badges63 bronze badges 6
  • Is this related? stackoverflow./questions/7208624/… . I would use the second answer – Joseph Young Commented Dec 21, 2015 at 23:10
  • 1 @JosephYoung I'm looking for a pure JavaScript solution because I'm planning to use this in relation to an algorithm that moves nodes around and I'm worried that JQuery might break the algorithm. I will read some of the answers though :) Thank you. – www139 Commented Dec 21, 2015 at 23:11
  • @JosephYoung All the answers for that question appear to contain JQuery. – www139 Commented Dec 21, 2015 at 23:13
  • If you know for sure that they are siblings, have you looked into using nextSibling? Starting with node A, you could write a simple function that uses nextSibling and check if it is indeed node B. If you iterate over all siblings and can't find node B, node A is the second. – Steve Commented Dec 21, 2015 at 23:14
  • @Steve Something I didn't mention (but I will add it right now to the question) is that these nodes are in the same level but may be many nodes between them. – www139 Commented Dec 21, 2015 at 23:15
 |  Show 1 more ment

2 Answers 2

Reset to default 7

Try pareDocumentPosition:

function theFirst(node1, node2) {
  return node1.pareDocumentPosition(node2)
    & Node.DOCUMENT_POSITION_FOLLOWING ? node1 : node2;
}

Note that if the nodes are in different trees, the result may be random (but consistent). You can filter out that case with & Node.DOCUMENT_POSITION_DISCONNECTED and return e.g. undefined.

Something like this should work

function isAfter(n1, n2) {
    var prev = n1.previousSibling,
        res  = true;

    while (prev) {
        if ( prev === n2 ) {
            prev = res = false;
        } else {
            prev = prev.previousSibling;
        }
    }
    return !!res;
}

Just iterate upwards using previousSibling (or downwards using nextSibling) from the first node, and pare against the second node to see if es after (or before) the first one.
When there's no more siblings, previousSibling returnsnull` and the loop ends.

FIDDLE

发布评论

评论列表(0)

  1. 暂无评论