This article describes the use of replace or modify function replaceChild() for DOM nodes. Share it for your reference. The specific analysis is as follows:
DOM node replacement process:
(1) Create a new node;
(2) Find the old node;
(3) From the perspective of the parent node, use the replaceChild (new, old) function to replace.
Copy the code as follows: <html>
<head>
<script type="text/javascript">
function t(){
//Thoughts: 1. First find the node to be replaced; 2. Create a new node; 3. Find the parent node and call the replaceChild (new, old) method from the perspective of the parent node.
var newli = document.createElement('li');//Create a new node
var newtext = document.createTextNode('Daytime');//Create text node
newli.appendChild(newtext);
var nodeul = document.getElementsByTagName('ul')[0];//Find the parent node
var oldli = nodeul.children[2];//Find the node to be replaced
nodeul.replaceChild(newli,oldli);//Replace
}
</script>
</head>
<body>
<div id="container">
<ul>
<li>Spring</li>
<li>Summer</li>
<li>Blue Sky</li>
<li>Autumn</li>
<li>Winter</li>
</ul>
</div>
<div id="copyul">
</div>
<hr />
<button onclick="t()" value="">Node replacement and modification</button>
</body>
</html>
I hope this article will be helpful to everyone's JavaScript programming.