【EASYDOM系列教程】之替換節點

Node 對象提供了 replaceChild() 方法實現 HTML 頁面中節點的替換功能。其語法結構以下:javascript

replacedNode = parentNode.replaceChild(newChild, oldChild);

在上述語法結構中,調用 replaceChild() 方法的 parentNode 表示被替換節點 oldChild 的父級節點。java

參數 oldChild 則表示 HTML 頁面中被替換的節點。replaceChild() 方法的返回值也是被替換的節點,即 oldChild == replaceNode。app

參數 newChild 則表示用於替換的新節點。若是該節點已經存在於 DOM 節點樹結構中的話,則它會被從原始位置刪除。學習

咱們能夠經過以下代碼示例,測試 replaceChild() 方法的具體使用:測試

// 獲取父節點
var parentNode = document.getElementById('parent');
// 建立新節點
var newChild = document.createElement('button');
newChild.setAttribute('class','button');
var text = document.createTextNode('A New Button');
newChild.appendChild(text);
// 獲取子節點
var oldChild = document.getElementById('btn');
// 替換節點
parentNode.replaceChild(newChild, oldChild);

本教程免費開源,任何人均可以避免費學習、分享,甚至能夠進行修改。但須要註明做者及來源,而且不能用於商業。spa

本教程採用知識共享署名-非商業性使用-禁止演繹 4.0 國際許可協議進行許可。code

圖片描述

相關文章
相關標籤/搜索