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


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

HTML DOM insertAdjacentElement() 方法在指定位置插入一個元素。

用法

以下是語法 -

使用 positionString 和 element 的參數調用 insertAdjacentElement()

node.insertAdjacentElement(“positionString”, element)

位置字符串

這裏,“positionString”可以是以下 -

位置字符串
描述
afterbegin
它在節點元素的開頭之後插入元素
afterend
它在節點元素之後插入元素
beforebegin
它在節點元素之前插入元素
beforeend
它在節點元素的末尾之前插入元素

示例

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

<!DOCTYPE html>
<html>  
<head>
<title>insertAdjacentElement()</title>
<style>
   form {
      width:70%;
      margin:0 auto;
      text-align:center;
   }
   * {
      padding:2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius:10px;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>insertAdjacentElement( )</legend>
<h1>Family Tree</h1>
<span id="Father">Father --></span>
<span id="GrandFather">Grand Father --></span>
<span id="Myself">Myself</span>
<input type="button" onclick="rectifyTree()" value="Correct Family Tree">
</fieldset>
</form>
<script>
   function rectifyTree() {
      var FSpan = document.getElementById("Father");
      var GFSpan = document.getElementById("GrandFather");
      GFSpan.insertAdjacentElement("afterend", FSpan);
   }
</script>
</body>
</html>

輸出

這將產生以下輸出 -

點擊前‘Correct Family Tree’按鈕 -

點擊後‘Correct Family Tree’按鈕 -

相關用法


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