【JavaScript】DOMを使ったHTML要素の参照

DOMスクリプティングで動的なアクションを与えるためには,まずHTML上に存在する要素をJavaScriptから特定できなければいけません。ここではDOMで規定されている各種手法を解説します。DOMを使ってHTMLの特定の要素を参照するために,次の三つのメソッドのいずれかを使います。

//引数で指定したIDのエレメントを配列として、すべて取り出して返す。
document.getElementById('id属性値');

//引数で指定したタグのエレメントを配列として、すべて取り出して返す。
document.getElementsByTagName('要素【タグ】名');

//引数で指定したname属性のエレメントを配列として、すべて取り出して返す
document.getElementsByName('name属性値');


それでは、以下のサンプルからDOMを手掛かりに要素を取り出して操作してみます。

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>DOMオブジェクト</title>
</head>

<body>
<h2 id="titleName">DOMオブジェクト</h2>
<ul>
<li>ハズレ</li>
<li>アタリ</li>
<li>ハズレ</li>
</ul>
<button onclick="addElement()">要素を追加</button>
<button onclick="removeElement()">要素を削除</button>
<button onclick="getElementsNum()">divの要素数</button>
<button onclick="replaceElement()">タイトル名の書き換え</button>
<button onclick="getElementValue()">リスト名の取得</button>
<div id="sample1"></div>
</body>

</html>

document.getElementsByTagNameの使い方

getElementsByTagNameをつかって引数にdivタグを指定することで要素数を求めます。Elementsと複数形になっているので記述する際は注意が必要です。
次は、引数で指定したliタグの2番目の要素(リストは0から始まる)を取り出してみます。要素内のテキストは,ドキュメントツリー上では,該当の要素の子要素(テキストノード)として構成されます。そのため,テキストを参照するためには,該当の要素の子要素を参照しnodeValueで要素内のデータを取り出します。

//document.getElementById
//document.getElementsTagName
function getElementsNum(){
  //引数で指定したdiv要素を変数eleDivに代入します
  var eleId = document.getElementById("sample1");
  var elmDiv = eleId.getElementsByTagName("div");
  //eleDivの要素数をアラート
        alert(elmDiv.length);
}

function getElementValue(){
	//liタグのリスト1に含まれる要素を取り出します
	var li = document.getElementsByTagName("li").item(1);
	//取り出した要素の子ノードにあるデータを取り出します
	var text = li.firstChild.nodeValue;
	alert(text);
	
        //以下の様に、記述することもできます。
	//alert(document.getElementsByTagName("li").item(1).firstChild.nodeValue);
}

/*
item:リストから番号を指定して要素を取り出す
firstChild:自分の一番最初の子要素を返す
nodeValue:要素内のデータを取り出す 
*/

document.getElementByIdの使い方

document.getElementByIdではid要素を指定することができます。createElement()をつかって指定したタグ要素を作成し、appendChild()で"id=sample2"のdiv要素を子ノードに追加します。

//document.getElementById
//createElement()
//appendChild()
function addElement(){
	//divタグを作成
	var element = document.createElement("div");
	//プロパティを追加
	element.id = "sample2";
	element.innerHTML = "テスト";
	element.style.backgroundColor = "black";
	element.style.color = "green";
	
	//変数objBodyに"id=sample1"を代入します
	var objBody = document.getElementById("sample1");
	//変数elementで指定した"id=sample2"のdiv要素を"子ノードに追加します
	objBody.appendChild(element);
}

removeChild()の使い方

addElement()で作成された"id=sample2"のdiv要素を削除します。

//removeChild()
function removeElement(){
	//変数elementに"id=sample1"の要素を代入します。
	var element = document.getElementById("sample1");
	//"id=sample1"の子ノードにある要素を削除します
	element.removeChild(element.childNodes.item(0));
}

innerHTMLの使い方

タイトルを「DOMオブジェクト」から「DOM(Document Object Model)」に書き換えます。

//innerHTML
function replaceElement(){
	title = document.getElementById("titleName");
	title.innerHTML = "DOM(Document Object Model)";
}

まとめ

同じような要素が他にたくさんある場合、getElementByIdメソッドを使って要素を特定し,それに対してgetElementsByTagNameメソッドを適用します。そうすることで,要素をサーチする範囲を限定することができ,目的の要素が簡単に取り出せるようになります。

以下に、今日の内容をまとめたソースを公開しておきます。実際に動作を確認することができます。

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />

<script type="text/javascript">
//document.getElementById
//document.getElementsTagName
function getElementsNum(){
  var eleId = document.getElementById("sample1");
  var elmDiv = eleId.getElementsByTagName("div");
        alert(elmDiv.length);
}

function getElementValue(){
	alert(document.getElementsByTagName("li").item(1).firstChild.nodeValue);
}

//document.getElementById
//createElement()
//appendChild()
function addElement(){
	var element = document.createElement("div");
	element.id = "sample2";
	element.innerHTML = "テスト";
	element.style.backgroundColor = "black";
	element.style.color = "green";

	var objBody = document.getElementById("sample1");
	objBody.appendChild(element);
}

//removeChild()
function removeElement(){
	var element = document.getElementById("sample1");
	element.removeChild(element.childNodes.item(0));
}

//innerHTML
function replaceElement(){
	title = document.getElementById("titleName");
	title.innerHTML = "DOM(Document Object Model)";
}

</script>
<title>DOMオブジェクト</title>
</head>
<body>

<h2 id="titleName">DOMオブジェクト</h2>
<ul>
<li>ハズレ</li>
<li>アタリ</li>
<li>ハズレ</li>
</ul>
<button onclick="addElement()">要素を追加</button>
<button onclick="removeElement()">要素を削除</button>
<button onclick="getElementsNum()">divの要素数</button>
<button onclick="replaceElement()">タイトル名の書き換え</button>
<button onclick="getElementValue()">リスト名の取得</button>
<div id="sample1">
</div>
</body>

</html>

ブラウザオブジェクトについて下記のサイトにリファレンスの一覧があります。実際にサンプルを見ながら動作を確認することができます。
JavaScriptリファレンス-ブラウザ関連クラス
http://javascriptist.net/docs/js_ref_ext.html