js insertBefore

 

 1     <select id="city" size="4" style="width:50px">
 2         <option id="hn">湖南</option>
 3         <option id="hb">湖北</option>
 4     </select>
 5       <script type="text/javascript">
 6           /*创建"新元素",插入到"湖南"元素之前
 7           var newOptionElement = document.createElement("option");
 8           newOptionElement.setAttribute("id","new");
 9           newOptionElement.innerHTML = "新元素";
10           var cityElement = document.getElementById("city");
11           var hnElement = document.getElementById("hn");        
12           cityElement.insertBefore(newOptionElement,hnElement);  //新元素
13         */  
14           //创建"新元素",插入到"湖南"元素之后
15           var newOptionElement = document.createElement("option");
16           newOptionElement.setAttribute("id","new");
17           newOptionElement.innerHTML = "新元素";
18           var cityElement = document.getElementById("city");
19           var hnElement = document.getElementById("hn");        
20             
21             //兄弟节点  nextSibling
22             cityElement.insertBefore(newOptionElement,hnElement.nextSibling);     
23      </script>

 

你可能感兴趣的:(insert)