javascriptメモ2

DOM操作

操作するHTML

<html>
  <head>
    <title>hogehoge</title>
  </head>
  <body onload="init();">
    <div>
      <h1>hogehoge</h1>
      <div id="test">
        <p>
          fuga
        </p>
        <div>
          piyo
        </div>
      </div>
    </div>
  </body>
</html>
var element = document.getElementById('test');
alert('id: ' + element.innerHTML);
/*
id: 
	<p>
	  fuga
	</p>
	<div>
	  piyo
	</div>
*/



var child_list = element.childNodes;
for (var i = 0; i < child_list.length; i++) {
        alert('childNodes: ' + child_list[i].nodeName);
}
/*
childNodes: #text
childNodes: P
childNodes: #text
childNodes: DIV
childNodes: #text
*/



 var tag_list = element.getElementsByTagName('div');
 for (var i = 0; i < tag_list.length; i++) {
         alert('TagName: ' + tag_list[i].nodeName);
 }
/*
TagName: DIV
*/




 var parent = element.parentNode;
 alert('parent: ' + parent.innerHTML);
/*
parent: 
<h1>hogehoge</h1>
<div id="test">
<p>
fuga
</p>
<div>
piyo
</div>
</div>
*/



 var previous = element.previousSibling;
 alert('previousSibling: ' + previous.nodeName);
/*
previousSibling: #text
*/




 var previous_previous = element.previousSibling.previousSibling;
 alert('previousSibling2: ' + previous_previous.nodeName);
/*
previousSibling2: H1
*/




 var first = element.firstChild;
 alert('firstChild: ' + first.nodeName);
/*
firstChild: #text
*/




 var last = element.lastChild;
 alert('lastChild: ' + last.nodeName);
/*
lastChild: #text
*/



// createElement, createTextNode, appendChild
 var new_div = document.createElement('div');
 var textNode = document.createTextNode('挿入テキスト');
 new_div.appendChild(textNode);
 alert('テキスト挿入');
 element.appendChild(new_div);




// replaceChild
 var replace_div = document.createElement('div');
 var textNode2 = document.createTextNode('入れ替えテキスト');
 replace_div.appendChild(textNode2);
 alert('テキスト入れ替え');
 element.replaceChild(replace_div, new_div);