HTML - DOM replaceChild() 方法



HTML DOM 的replaceChild()方法允許您用另一個子元素(即新子元素)替換父元素中的一個子元素(即舊子元素)。

newChild 可以是任何型別的節點(元素、文字、註釋等),而 oldChild 必須是 parentNode 的子元素。如果 oldChild 不是 parentNode 的子元素,則此方法將丟擲 NotFoundError。

語法

以下是 HTML DOM replaceChild() 方法的語法:

parentElement.replaceChild(newChild, oldChild);

引數

此方法接受如下所述的兩個引數:

引數 描述
newChild 將替換現有(舊)子元素的新子元素。
oldChild 將被替換的現有子元素。

返回值

此方法返回已從父元素中刪除的被替換的子元素。

示例 1:用新元素替換段落

以下示例演示了 HTML DOM replaceChild() 方法的使用方法,該方法在單擊按鈕時使用新內容替換段落(<p>):

<![DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM replaceChild()</title>
<style>
   button{
      padding: 10px;
   }
</style>
</head>
<body>
<p>Click the button to replace the paragraph with a new div.</p>
<div id="content">
<p id="currentPara">This is a paragraph.</p>
</div>
<button onclick="replaceParagraph()">Replace Paragraph</button>
<script>
   function replaceParagraph() {
      const newDiv = document.createElement('div');
      newDiv.textContent = 'This is a new div element';
      const content = document.getElementById('content');
      const currentPara = document.getElementById('currentPara');
      content.replaceChild(newDiv, currentPara);
   }
</script>
</body>
</html>

示例 2:替換列表項

以下是 HTML DOM replaceChild() 方法的另一個示例。我們使用此方法用新的列表項替換列表 (<li>) 項:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM replaceChild()</title>
<style>
   button{
      padding: 10px;
   }
</style>
</head>
<body>
<p>Click the button to replace the first list item with a new list item.</p>
<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
</ul>
<button onclick="replaceListItem()">Replace List Item</button>
<script>
   function replaceListItem() { 
       const nI=document.createElement('li');
       nI.textContent = 'New Item';
       // Get reference to the list and the first list item
       const mL=document.getElementById('myList');
       const fi=mL.querySelector('li:first-child');
       // Replace the first list item with the new list item
       mL.replaceChild(nI, fi);
   }
</script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
replaceChild()
html_dom_element_reference.htm
廣告