HTML
replaceChild() 方法可將某個子節點替換為另一個。 新節點可以是文字中已存在的,或是你新建立的。 node.replaceChild(newChild, oldChild); Example:
<>input type="button" id="inn" value="replaceChild div to textarea" onclick="change()"> <>div id="ID">this is div or textarea<>/div> <>script> function change() { var Tag = document.getElementById("ID").tagName ; if(Tag=="DIV"){ var textarea = document.createElement("textarea"); textarea.innerHTML = ID.innerHTML; textarea.id= ID.id; ID.parentNode.replaceChild(textarea, ID); } else{ var div = document.createElement("div"); div.innerHTML = ID.innerHTML; div.id= ID.id; ID.parentNode.replaceChild(div, ID); } } <>/script>
<>div id="myList"> <>span >1111<>/span > <>span >2222<>/span > <>span >3333<>/span > <>span >4444<>/span > <>span >5555<>/span > <>/div> <>button onclick="myFunction()">span ⇋ div <>/button> <>script> function myFunction() { var It=document.getElementById("myList"); if(It.children[0].nodeName=="SPAN"){ for(var xx=0 ; xx<It.children.length ; xx++){ var div=document.createElement("div") var text=document.createTextNode(It.children[xx].innerHTML); div.appendChild(text); It.replaceChild(div, It.children[xx]); } } else { for(var xx=0 ; xx<It.children.length ; xx++){ var span=document.createElement("span") var text=document.createTextNode(It.children[xx].innerHTML); span.appendChild(text); It.replaceChild(span, It.children[xx]); } } } <>/script> <>style> #myList span {color:blue } #myList div {color:darkred} <>/style>