當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


HTML DOM insertBefore()用法及代碼示例

HTML DOM insertBefore() 方法在已經存在的子節點之前插入一個新節點。

用法

以下是語法 -

使用 positionString 和 text 參數調用 insertBefore()

node.insertBefore(newNode, existingNode)

這裏,parameters可以是以下 -

參數

參數描述
newNode它是新創建的子節點,要附加在開頭
existingNode它是已經存在的節點

示例

讓我們看一個例子InsertBefore()方法 -

<!DOCTYPE html>
<html>
<head>
<title>insertBefore()</title>
<style>
   form {
      width:70%;
      margin:0 auto;
      text-align:center;
   }
   * {
      padding:2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius:10px;
   }
   ol {
      width:30%;
      margin:0 auto;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>insertBefore( )</legend>
<h1>How to make tea</h1>
<h3>Steps:</h3>
<ol id="stepList">
<li>Add Tea Bag</li>
<li>Add Sugar</li>
<li>Add Milk</li>
</ol>
<input type="button" onclick="addStep()" value="Add">
</fieldset>
</form>
<script>
   function addStep() {
      var newIngredient = document.createElement("LI");
      var textnode = document.createTextNode("Boil Water");
      newIngredient.appendChild(textnode);
      var stepList = document.getElementById("stepList");
      stepList.insertBefore(newIngredient, stepList.childNodes[0]);
   }
</script>
</body>
</html>

輸出

這將產生以下輸出 -

點擊前‘Add’按鈕 -

點擊後‘Add’按鈕 -

相關用法


注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM insertBefore() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。