HTML DOMナビゲーション
HTML DOMを通じて、あなたはノードナビゲーションツリーの関係にノードを使用することができます。
HTML DOMノードリスト
getElementsByTagNameの()メソッドは、 ノードのリストを返します。 ノードリストは、ノードの配列です。
次のコードは、選択された文書のすべての<P>ノード:
例
var
x=document.getElementsByTagName("p");
これは、次のラベルによってアクセスすることができます。 <P>第二にアクセスするには、次のように書くことができます。
y=x[1];
»をお試しください
注意:
ラベルの下に0から始まります。
HTML DOMノードリストの長さ
長さ属性は、ノードリスト内のノードの数を定義します。
あなたは、ループノードリストにlengthプロパティを使用することができます。
例
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
»をお試しください
分析の例:
- すべての<p>要素ノードを取得
- テキストノードの各<p>要素の出力値
ナビゲーションノードの関係
次の3つのノード属性を使用することができますのparentNode、のfirstChildとlastChildは、文書構造をナビゲート。
次のHTMLフラグメントを考えてみましょう。
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates node relationships.</p>
</div>
</body>
</html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates node relationships.</p>
</div>
</body>
</html>
- 最初の<p>要素は、<body>要素(のfirstChild)の最初の子であります
- <div>要素は、最後の子要素は、<body>要素(lastChild)
- <Body>要素は、最初の<p>要素と<div>要素の親ノード(のparentNode)であります
firstChildプロパティは、テキストの要素にアクセスするために使用することができます。
例
<html>
<body>
<p id="intro">Hello World!</p>
<script>
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>
<body>
<p id="intro">Hello World!</p>
<script>
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>
»をお試しください
DOMのルートノード
あなたはドキュメントのすべてにアクセスできる2つの特別な属性があります:
- document.firstChild - すべての文書
- document.body - 文書の本文
例
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>
</html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>
</html>
»をお試しください
childNodesとのnodeValue
innerHTMLプロパティに加えて、要素の内容を取得するためのchildNodesとのnodeValueプロパティを使用することができます。
次のコードは、ID = "イントロ" <p>要素の値を取得します。
例
<html>
<body>
<p id="intro">Hello World!</p>
<script>
var txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
</html>
<body>
<p id="intro">Hello World!</p>
<script>
var txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
</html>
»をお試しください
childNodesとのnodeValueは性質がある一方で、上記の例では、getElementByIdのは、方法です。
このチュートリアルでは、innerHTMLプロパティを使用します。 しかし、上記の学習方法は、DOMツリー構造と理解をナビゲートするのに役立ちます。