■ はじめに
https://dk521123.hatenablog.com/entry/2011/01/07/012520
の続き。
【1】要素の操作
ポイント
* document.getElementById()を利用する => 指定したIDの要素のオブジェクト取得
1)サンプル
例1
<html> <head> <title>サンプル</title> <script type="text/javascript"> function sample() { var resultValue = document.getElementById("inputId").value; alert('あなたの入力した値:' + resultValue); } </script> </head> <body> <form name="form1" id="id_form1" action=""> <p><label>入力欄:<input name="textBox1" id="inputId" type="text" value="" /></label></p> <input type="button" value="Click Me!" onclick="sample();" /> </form> </body> </html>
例2
<html> <head> <title>サンプル</title> <script type="text/javascript"> function sample() { var element = document.getElementById("here") element. innerHTML = '<div id="here">押した?</div>'; } </script> </head> <body> <button onclick="sample()">ボタン押下で「ここに表示」が「押した?」に変わる</button> <div id="here">ここに表示</div> </body> </html>
【2】子要素のリストを取得
1)サンプル
function findChildrenElements(targetID) { var element = document.getElementById(targetID); var children = element.childNodes; alert("1番目の子要素 : " + children[0].innerHTML + " ."); }
補足:innerHTMLについて
* 特定のHTML要素の中身を動的に書き換える <p id="example">HERE</p> があったとして、 document .getElementById ('example'). innerHTML = '<p>TEST IS SUCCESSFUL!</p>'; を実行させれば、『<p id="example">HERE</p>』は、動的に『<p>TEST IS SUCCESSFUL!</p>』に変わる。
参考文献
http://www.openspc2.org/reibun/javascript2/DOM/node/0005/index.html
http://javascriptist.net/ref/element.childNodes.html
innerHTML
http://www.nishishi.com/javascript/2007/innerhtml.html
http://park.geocities.jp/gdfsm000/ireport/ireport04.html
【3】子要素を全て削除
1)サンプル
function removeAllChildrenElements(targetID) { var element = document.getElementById(targetID); while(element.firstChild){ element.removeChild(element.firstChild); } }
参考文献
関連記事
DOM ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2011/01/07/012520
JavaScript覚書
https://dk521123.hatenablog.com/entry/2010/01/15/191626