1. 程式人生 > >DOM對HTML元素增刪改查的操作1

DOM對HTML元素增刪改查的操作1

 程式碼:

1.節點的增刪改查操作

<!DOCTYPE html>
<html>
 <head>
  <title>建立元素</title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">

  <script type="text/javascript">
     function create(){
      var city=document.getElementById("city");
	  var element=document.createElement("li");
	  element.innerHTML="南京";
	  //city.appendChild(element);//插入節點
	  //city.insertBefore(element,city.firstChild.nextSibling);
	 // city.replaceChild(element,city.firstChild.nextSibling);//替換節點
	 }

	 function copy(){
      var city=document.getElementById("city");
	  var element=city.firstChild.nextSibling.cloneNode(true);
	  city.appendChild(element);
	 }

	 function del(){
      var city=document.getElementById("city");
	  var element=city.firstChild.nextSibling;
	  city.removeChild(element);
	 }
   </script>
 </head>
 <body>
   <ul id="city">
    <li>北京</li>
    <li>上海</li>

	<input type="button" value="建立複製替換節點"  onclick="create()"/>
    <input type="button" value="複製節點"  onclick="copy()"/>
	<input type="button" value="刪除節點" onclick="del()"/>
   </ul>
 </body>
</html>
2.列表框,下拉列表框的增刪改查
<!DOCTYPE html>
<html>
 <head>
  <title>建立元素</title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">

  <script type="text/javascript">
    function createSelect(){
	 var element=document.createElement("select");
	 for(var i=0;i<10;i++)
	 {
      var op=new Option("新增的選項"+i,i);
	  element.options[i]=op;
	 }
	 element.size=5;//顯示屬性的一半
	 element.id="city";
	 document.getElementById("test").appendChild(element);
	}

	function delOne(){
     var city=document.getElementById("city");
	 if(city.options.length>0)
	 {
       //city.remove(city.options.length-1);
	   city.options[city.options.length-1]=null;//刪除列表的第二種方式
	 }
	}

	function clearAll(){
	 var city=document.getElementById("city");
     if(city.options.length>0)
	 {
       city.options.length=0;
	 }
	}
  </script>
 </head>
 <body id="test">
   <input type="button" value="建立一個城市列表框" onclick="createSelect()"/>
   <input type="button" value="一條條刪除列表框內容" onclick="delOne()"/>
   <input type="button" value="一次性清空列表框內容" onclick="clearAll()"/>
   
 </body>
</html>


知識點總結: