2012年12月2日日曜日

TypeScript で DOM 操作

helloworld1.html
  1. <!DOCTYPE html>  
  2. <html>  
  3.  <head>  
  4.   <meta charset="utf-8" />  
  5.   <title>hello world 1</title>  
  6.  </head>  
  7.  <body>  
  8.   <h1>Hello World 1</h1>  
  9.   <input type="button" id="button1" value="pick h1 tag text" />  
  10.     
  11.     
  12.   <div id="authors">  
  13.    <div>芥川 竜之介</div>  
  14.    <div>夏目 漱石</div>  
  15.    <div></div>  
  16.    <div>江戸川 乱歩</div>  
  17.   </div>  
  18.   <input type="button" id="button2" value="pick all authors" />  
  19.   
  20.   <script src="helloworld1.js"></script>  
  21.   
  22.  </body>  
  23. </html>  


helloworld1.ts
  1. function helloworld1(e : MouseEvent) {  
  2.  var h1Elm : Node = document.getElementsByTagName('h1')[0];  
  3.  var textNode : Node = h1Elm.childNodes[0];  
  4.  var text : string = textNode.nodeValue;  
  5.  alert(text);  
  6. }  
  7.   
  8. function helloworld2(e : MouseEvent) {  
  9.  var authorsElem : Node = document.getElementById('authors');  
  10.  var authors = new Array();  
  11.  for (var i = 0; i < authorsElem.childNodes.length; i++) {  
  12.   var node = authorsElem.childNodes.item(i);  
  13.   if(node.nodeType != 1) {  
  14.    continue;  
  15.   }  
  16.   if(!node.hasChildNodes()) {  
  17.    continue;  
  18.   }  
  19.   if(node.firstChild.nodeType != 3) {  
  20.    continue;  
  21.   }  
  22.   authors.push(node.firstChild.nodeValue);  
  23.  }  
  24.  alert(authors.join("\n"));  
  25. }  
  26.   
  27. var btn1 : HTMLElement = document.getElementById("button1");  
  28. btn1.addEventListener("click", helloworld1, false);  
  29.   
  30. var btn2 : HTMLElement = document.getElementById("button2");  
  31. btn2.addEventListener("click", helloworld2, false);  
ノードの種類nodeTypenodeNamenodeValue
要素ノード1タグ名null
属性ノード2属性名属性値
テキストノード3#textテキストの内容
コメントノード8#commentコメントの内容
ドキュメントノード9#documentnull

0 件のコメント:

コメントを投稿