Node.compareDocumentPosition() - Web APIs 编辑

The Node.compareDocumentPosition() method reports the position of the given node relative to another node in any document — not just the given node’s document.

The return value is a bitmask of the following values:

NameValue
DOCUMENT_POSITION_DISCONNECTED1
DOCUMENT_POSITION_PRECEDING2
DOCUMENT_POSITION_FOLLOWING4
DOCUMENT_POSITION_CONTAINS8
DOCUMENT_POSITION_CONTAINED_BY16
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC32

Syntax

compareMask = node.compareDocumentPosition(otherNode)

Parameters

otherNode
The other Node with which to compare the first node’s document position.

Return value

An integer value whose bits represent the otherNode's relationship to the calling node.

More than one bit is set if multiple scenarios apply. For example, if otherNode is located earlier in the document and contains the node on which compareDocumentPosition() was called, then both the DOCUMENT_POSITION_CONTAINS and DOCUMENT_POSITION_PRECEDING bits would be set, producing a value of 10 (0x0A).

Example

const head = document.head;
const body = document.body;

if (head.compareDocumentPosition(body) & Node.DOCUMENT_POSITION_FOLLOWING) {
  console.log('Well-formed document');
} else {
  console.error('<head> is not before <body>');
}

Note: Because the result returned by compareDocumentPosition() is a bitmask, the bitwise AND operator must be used for meaningful results.

Specifications

SpecificationStatusComment
DOM
The definition of 'Node.compareDocumentPosition()' in that specification.
Living Standard
Document Object Model (DOM) Level 3 Core Specification
The definition of 'Node.compareDocumentPosition()' in that specification.
ObsoleteInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:102 次

字数:3998

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文