HTML DOM compareDocumentPosition()メソッド
HTML DOMのcompareDocumentPosition()メソッドは、特定のノード位置を任意のドキュメント内の他のノードと比較するために使用されます。このメソッドの戻り型は、ドキュメント内での位置を表す整数型です。整数の戻り値は指定どおりです-
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.
構文
以下は、HTML DOMのcompareDocumentPosition()メソッドの構文です-
node.compareDocumentPosition(node)
ここで、ノードはノードオブジェクトタイプであり、現在のノードと比較するノードを指定します。
例
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> 出力
これにより、次の出力が生成されます-
POSITIONボタンをクリックすると-
上記の例では-
最初に2つ作成しました
IDが「para1」および「para2」の要素。
<p id="para1">This is a paragraph</p> <p id="para2">This is another paragraph</p>
次に、ユーザーがクリックするとdocPosition()メソッドを実行するボタンPOSTIONを作成しました-
<button onclick="docPosition()">POSITION</button>
docPosition()メソッドは、ドキュメントオブジェクトのgetElementById()メソッドを使用して両方の
要素を取得します。次に、両方の段落のlastchildプロパティ値をそれぞれ変数p1とp2に割り当てます。
次に、p1をパラメーターとしてp2でcompareDocumentPosition()メソッドを呼び出します。これは、p1に対するp2の位置を比較したいことを意味します。ここでは、p2はp1の後に配置されているため、戻り値は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;
} -
HTML DOM writeln()メソッド
HTML DOM writeln()は、複数の式(HTMLまたはJavaScript)をドキュメントに直接書き込む機能をユーザーに提供します。 注 −このメソッドは、ドキュメント内のHTMLコードがある場合はそれを上書きし、新しい行に引数を追加します。 構文 以下は構文です- document.write(agruments) 例 HTML DOMドキュメントのwriteln()メソッドの例を見てみましょう- <!DOCTYPE html> <html> <head> <title>HTML DOM writeln()</title&g
-
HTML DOM write()メソッド
HTML DOM write()は、複数の式(HTMLまたはJavaScript)をドキュメントに直接書き込む機能をユーザーに提供します。 注 −このメソッドは、ドキュメント内のHTMLコードがある場合はそれを上書きし、新しい行に引数を追加しません。 構文 以下は構文です- document.write(arguments) 例 HTML DOMドキュメントのwrite()メソッドの例を見てみましょう- <!DOCTYPE html> <html> <head> <title>HTML DOM write()</title> &l