DIV CSS 佈局教程網

DOM 程式設計:動態建立與刪除元素的做法
編輯:JavaScript基礎知識     

動態建立與刪除節點是 DOM 操作的基本功。以下用「建立一個超連結,再把它刪掉」作為範例。

版本一:直接使用 getElementById

<html>
<head>
<script type="text/javascript">
  function test() {
    // createElement() 建立一個指定標籤名稱的元素(例如動態建立超連結)
    var createa = document.createElement("a");
    createa.id = "a1";
    createa.innerText = "連接到百度";
    createa.href = "https://www.baidu.com";

    // 設定顏色時別忘了 style 屬性,否則沒有效果
    createa.style.color = "green";

    // 加入預設位置(body)並作為子節點
    // document.body.appendChild(createa);

    // 放到指定位置
    document.getElementById("div1").appendChild(createa);
  }

  function test2() {
    // 於指定位置刪除節點:removeChild()
    // 若 id 重複,js 只取第一個
    document.getElementById("div1").removeChild(document.getElementById("a1"));
  }
</script>
</head>
<body>
<!-- 動態建立元素 -->
<input type="button" value="建立一個 a 標籤" onclick="test()" /><br/>
<input type="button" value="刪除建立的 a 標籤" onclick="test2()" />
<div id="div1" style="width:400px;height:300px;border:1px solid silver">
</div>
</body>
</html>

版本二:封裝 $() 簡化取值

每次都要寫 document.getElementById() 相當冗長,實務上幾乎都會先封裝一個小函式:

<html>
<head>
<script type="text/javascript">
  // 定義一個函式,回傳指定 id 的物件
  function $(id) {
    return document.getElementById(id);
  }

  function test() {
    // createElement() 建立一個指定標籤名稱的元素
    var createa = document.createElement("a");
    createa.id = "a1";
    createa.innerText = "連接到百度";
    createa.href = "https://www.baidu.com";
    createa.style.color = "green";

    // 放到指定位置
    $("div1").appendChild(createa);
  }

  function test2() {
    // 於指定位置刪除節點
    $("div1").removeChild($("a1"));
  }
</script>
</head>
<body>
<!-- 動態建立元素 -->
<input type="button" value="建立一個 a 標籤" onclick="test()" /><br/>
<input type="button" value="刪除建立的 a 標籤" onclick="test2()" />
<div id="div1" style="width:400px;height:300px;border:1px solid silver">
</div>
</body>
</html>

幾個實務上會遇到的細節

removeChild 必須指名父節點。這是 DOM Level 1 的設計——節點本身不知道自己的父親是誰以外的資訊,因此刪除時要由父節點來執行。若要刪除自己不確定父節點的物件,可以寫成 node.parentNode.removeChild(node)。

innerText 不是標準屬性。它在 Firefox 早期版本中不受支援,跨瀏覽器時應改用 textContent;若建立的是需要 HTML 的內容才用 innerHTML,但要注意 XSS 風險。

用 style 屬性設樣式會覆蓋既有設定。範例中 createa.style.color = "green" 只動到 color 一個屬性還好,但若是 createa.style.cssText = ... 就會整批覆寫。較好的做法是替元素加上 class,再用 CSS 控制外觀,讓樣式與行為分離。

Modern 的替代寫法。今天更常用的做法包括:insertAdjacentHTML() 以字串插入並指定位置(beforebegin/afterbegin/beforeend/afterend)、replaceChildren() 一次換掉所有子節點、Element.remove() 直接自刪而不必找父節點。这些方法程式碼更短、語意更清楚,也省去不少跨瀏覽器的判斷。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved