在重慶結點前插入新結點天津

<ul>
  <li id="bj" name="beijing">北京</li>
<li id="sh" name="shanghai">上海</li>
<li id="cq" name="chongqing">重慶</li>
</ul>

 在 <li id="cq" name="chongqing">重慶</li>的前面, 插入新的節點 <li id="tj" name="tianjin">天津</li>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>insertBefore</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
  <body>
       <ul>
  <li id="bj" name="beijing">北京</li>
<li id="sh" name="shanghai">上海</li>
<li id="cq" name="chongqing">重慶</li>
  </ul>
  </body>
  
  <script language="JavaScript">
  // 在 <li id="cq" name="chongqing">重慶</li>的前面
  // 插入新的節點 <li id="tj" name="tianjin">天津</li>
//創建"天津節點"
     var tjElement=document.createElement("li");
tjElement.setAttribute("id","tj");
tjElement.setAttribute("name","tianjin");
var textElement=document.createTextNode("天津");
tjElement.appendChild(textElement);
//獲取"重慶"節點
var cqElement=document.getElementById("cq");
//獲取重慶節點的父節點
var cqParentElement=cqElement.parentNode;
//添加到重慶節點的前面
cqParentElement.insertBefore(tjElement,cqElement);
  </script>
</html>

如果在上海結點前插入新結點,需要獲取上海結點的下一個兄弟結點,判斷一下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>insertBefore.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
  </head>
  <body>
       <ul>
  <li id="bj" name="beijing">北京</li>
<li id="sh" name="shanghai">上海</li>
<li id="cq" name="chongqing">重慶</li>
  </ul>
  </body>
  <script language="JavaScript">
  // 插入新的節點 <li id="tj" name="tianjin">天津</li>
// 在  <li id="sh" name="shanghai">上海</li>的後面
//創建"天津節點"
     var tjElement=document.createElement("li");
tjElement.setAttribute("id","tj");
tjElement.setAttribute("name","tianjin");
var textElement=document.createTextNode("天津");
tjElement.appendChild(textElement);
//獲取"上海"節點
var shElement=document.getElementById("sh");
//獲取上海節點的父節點
var shParentElement=shElement.parentNode;
//獲取上海節點的下一個兄弟節點
var shNextElement=shElement.nextSibling;
//添加上海節點的後面
shParentElement.insertBefore(tjElement,shNextElement);
  </script>
</html>
發佈了34 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章