Computer >> Máy Tính >  >> Lập trình >> HTML

Phương thức HTML DOM so sánhDocumentPosition ()

Phương thức HTML DOM CompareDocumentPosition () được sử dụng để so sánh một vị trí nút nhất định với bất kỳ nút nào khác trong bất kỳ tài liệu nào. Kiểu trả về của phương thức này là kiểu số nguyên để mô tả vị trí của chúng trong tài liệu. Các giá trị trả về số nguyên như được chỉ định -

1: No relationship, the two nodes do not belong to the same document.
2: The first node (para1) is positioned after the second node (para2).
4: The first node (para1) is positioned before the second node (para2).
8: The first node (para1) is positioned inside the second node (para2).
16: The second node (para2) is positioned inside the first node (para1).
32: No relationship, or the two nodes are two attributes on the same element.

Cú pháp

Sau đây là cú pháp cho phương thức HTML DOM CompareDocumentPosition () -

node.compareDocumentPosition(node)

Ở đây, nút thuộc loại đối tượng nút và chỉ định nút mà chúng ta muốn so sánh với nút hiện tại.

Ví dụ

Chúng ta hãy xem một ví dụ cho phương thức CompareDocumentPosition () -

<!DOCTYPE html>
<html>
<body>
<p id="para1">This is a paragraph</p>
<p id="para2">This is another paragraph</p>
<p>Click the button to compare the position of the two paragraphs.</p>
<button onclick="docPosition()">POSITION</button>
<p id="Sample"></p>
<script>
   function docPosition() {
      var p1 = document.getElementById("para1").lastChild;
      var p2 = document.getElementById("para2").lastChild;
      var x = p2.compareDocumentPosition(p1);
      document.getElementById("Sample").innerHTML = x;
   }
</script>
</body>
</html>

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Phương thức HTML DOM so sánhDocumentPosition ()

Khi nhấp vào nút VỊ TRÍ -

Phương thức HTML DOM so sánhDocumentPosition ()

Trong ví dụ trên -

Đầu tiên chúng tôi đã tạo hai

các phần tử có id “para1” và “para2”.

<p id="para1">This is a paragraph</p>
<p id="para2">This is another paragraph</p>

Sau đó, chúng tôi đã tạo một nút POSTION sẽ thực thi phương thức docPosition () khi được người dùng nhấp vào -

<button onclick="docPosition()">POSITION</button>

Phương thức docPosition () nhận cả phần tử

bằng cách sử dụng phương thức getElementById () trên đối tượng tài liệu. Sau đó, nó sẽ gán giá trị thuộc tính con cuối cùng của cả hai đoạn cho biến p1 và p2 tương ứng.

Sau đó, chúng tôi gọi phương thức CompareDocumentPosition () trên p2 với p1 là tham số. Điều này có nghĩa là chúng ta muốn so sánh vị trí của p2 đối với p1. Vì ở đây p2 được đặt sau p1 nên giá trị trả về là 2 -

function docPosition() {
   var p1 = document.getElementById("para1").lastChild;
   var p2 = document.getElementById("para2").lastChild;
   var x = p2.compareDocumentPosition(p1);
   document.getElementById("Sample").innerHTML = x;
}