HTML要素を追加する
Ajaxなどを利用してWebAPIサービス等と連携する場合、動的にHTML要素を追加し、受け取ったデータを表示することがある。
<script type="text/javascript"> //JSON形式で画像情報をセットする var images = { image01 : { src: "images/image01.jpg", width: 200, height: 133, alt: "image01", className: "image" } } window.onload = function(){ document.getElementById("trigger").onclick = function(){ addElement("image-container", images); } } </script> </head> <body> <h1>HTML要素を追加する</h1> <input id="trigger" type="button" value="画像を表示する" /> <div id="image-container"> <!-- ここにimg要素が追加される --> </div>
//1つ目の引数は親ノードのID名、2つ目は画像情報 function addElement(container, images){ for(var index in images){ //createElementメソッドでimg要素オブジェクトを生成する var newImage = document.createElement("img"); newImage.src = images[index].src; newImage.width = images[index].width; newImage.height = images[index].height; newImage.alt = images[index].alt; newImage.className = images[index].className; //appendChildメソッドを利用してnewImageを親ノードに追加する document.getElementById(container).appendChild(newImage); } }