캠핑과 개발

메소드
new
Element(tagName[, attributes])


예제
<a class="link" href="/popup.html">팝업열기</a>

일반 스크립트
var ele = document.createElement('a');
ele.setAttribute('class', 'link');
ele.setAttribute('href', '/popup.html');
ele.appendChild(document.createTextNode("팝업열기"));

prototype를 이용한 스크립트
var a = new Element('a', { 'class': 'link', href: '/popup.html' }).update("팝업열기");



엘리먼트 추가, 삭제 예제

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">
<head>
 <title> new document </title>
 <meta name="generator" content="editplus" />
 <meta name="generator" content="editplus" />
 <meta name="author" content="" /> 
 <meta http-equiv="keywords" content="enter,your,keywords,here" />
 <meta http-equiv="description" content="A short description of this page." />
 <meta http-equiv="content-type" content="text/html; charset=EUC-KR" />
 <script type="text/javascript">
 var count = 0;
 /**
 * 아이템 추가
 */
 function appendItem(){
  count++;
  var newItem = document.createElement("div");
  newItem.setAttribute("id", "item_" + count);
  var html = '새로 추가된 아이템['+count+'] <input type="button" value="삭제" onclick="removeItem('+ count +')" />';
  newItem.innerHTML = html;

  var itemListNode = document.getElementById('itemList');  
  itemListNode.appendChild(newItem);
  
 }
 /**
 * 아이템 삭제
 */
 function removeItem(idCount){
  var item = document.getElementById("item_" + idCount);
  if(item != null){
   item.parentNode.removeChild(item);
  }
 }
 </script>
</head>
<body>
 <input type="button" value="추가" onclick="appendItem()" />
 <div id="itemList"></div>
</body>
</html>