Hello, please help understand the principle of compareDocumentPosition ().

Experimented in the console:

var div=document.createElement('div'); div.innerHTML="<span><span><span><span><span>span</span></span></span></span></span> div.appendChild(document.createElement('p')) 

It turned out this:

 <div> ​<span> ​<span> ​<span> ​<span> ​<span>"s"​</span>​ </span> ​</span> ​</span>​ </span> ​<p>​</p> ​</div>​ 

Now apply nodeA.compareDocumentPosition(nodeB)

 r = div.childNodes[0].compareDocumentPosition(div.childNodes[1])//r=4 r.toString(2)="100" 

Everything is clear here, nodeA precedes nodeB

But the next result is not clear to me.

 r1 = div.childNodes[0].compareDocumentPosition(div) //r1=10 r1.toString(2)="1010" r2 = div.childNodes[0].childNodes[0].compareDocumentPosition(div) //r2=10 r2.toString(2)="1010" 

Actually a question. Why is the result 10 and not 8 (nodeB contains nodeA), and what does 10 mean? Also, should the results of r1 and r2 not be different? (the nesting level is different)

    1 answer 1

    Question : Почему результат 10 а не 8 (nodeB содержит nodeA), и что значит 10?
    Answer :

    The compareDocumentPosition method provides information about the content and relative order of elements simultaneously.

     Биты Число Значение 000000 0 nodeA и nodeB -- один и тот же узел 000001 1 Узлы в разных документах (или один из них не в документе) 000010 2 nodeB предшествует nodeA (в порядке обхода документа) 000100 4 nodeA предшествует nodeB 001000 8 nodeB содержит nodeA 010000 16 nodeA содержит nodeB 100000 32 Зарезервировано для браузера 

    The concept of "precedes" means not only "the previous neighbor with a common parent", but also has a more general meaning: "it occurs earlier in the order of direct traversal of the document tree.

    The result 1010 means that the node precedes and simultaneously contains.


    Question : Should the results of r1 and r2 not be different? (the nesting level is different)
    Answer : The check is carried out on the fact of nesting, and not on the depth of nesting. therefore no, the result should not differ.

    Source: compareDocumentPosition

    • Not nested, but contains - Grundy
    • Saw the table, so this is 000010 + 001000 = 001010 I reason correctly? But why does it precede, is it simply embedded, or not? - Jarry Roxwell
    • @JarryRoxwell supplemented the preceding answer. about arithmetic - yes, that's right - lexxl
    • one
      because the method in question provides both information on the content and on the relative order of the elements. - lexxl
    • one
      @JarryRoxwell do not know about this. probably it will have to use brute force / recursion / ... - lexxl