Home > Web Front-end > JS Tutorial > body text

Introduction to using replaceChild() to replace existing elements with javascript_javascript skills

WBOY
Release: 2016-05-16 16:53:28
Original
1962 people have browsed it

replaceChild(a,b) is used to replace existing elements in the document.
Parameter a: the node to be inserted,
Parameter b: the node to be replaced

Copy code The code is as follows:

var oDiv = document.getElementById("guoDiv");
var oSpan = document.createElement("span ");
oSpan.innerHTML = "4";
var firsChild = oDiv.firstElementChild ? oDiv.firstElementChild : oDiv.firstChild
var returnNode = oDiv.replaceChild(oSpan, firsChild); //Replace the first element An element, returns the replaced element
alert(returnNode.innerHTML); //1
var lastChild = oDiv.lastElementChild ? oDiv.lastElementChild : oDiv.lastChild;
oSpan = document.createElement( "span");
oSpan.innerHTML = "5";
returnNode = oDiv.replaceChild(oSpan, lastChild); //Replace the last one and return the replaced element
alert(returnNode.innerHTML );//3

Copy code The code is as follows:

< ;div id="guoDiv">
1
2
3
< /div>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template