Node replacement:
1). replaceChild (): replace one subnode in a given parent element with another subnode.
Var reference = element. replaceChild (newChild, oldChild );
The returned value is a reference pointer pointing to the child node that has been replaced.
2) In addition to the replacement function, the node also has the function of moving.
3) This method can only complete one-way replacement. If bidirectional replacement is required, you need to define a function:
/**
* Swap aNode and bNode
* @ Param {Object} aNode
* @ Param {Object} bNode
*/
Function replaceEach (aNode, bNode ){
If (aNode = bNode ){
Return;
}
Var aParentNode = aNode. parentNode;
// If aNode has a parent node
If (aParentNode ){
Var bParentNode = bNode. parentNode;
// If bNode has a parent node
If (bParentNode ){
Var tempNode = aNode. cloneNode (true );
BParentNode. replaceChild (tempNode, bNode );
AParentNode. replaceChild (bNode, aNode );
}
}
}
Html code
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Untitled Document </title>
<Script type = "text/javascript">
Window. onload = function (){
// 1. Replace the "Tokyo" node with "Pyongyang"
Var pr = document. createElement ("li ");
Pr. appendChild (document. createTextNode ("Pyongyang "));
Document. getElementById ("city"). replaceChild (pr, document. getElementById ("dj "));
// 2. Implement the interchange between # bj and # rl. The cloneNode () method must be used.
Var bj = document. getElementById ("bj ");
Var rl = document. getElementById ("rl ");
//
// Var city = document. getElementById ("city ");
// Var game = document. getElementById ("game ");
//
// City. replaceChild (rl. cloneNode (true), bj );
// Game. replaceChild (bj, rl );
ReplaceEach (rl, bj );
};
/**
* Swap nodes
* @ Param {Object} aNode
* @ Param {Object} bNode
*/
Function replaceEach (aNode, bNode ){
Var aParentNode = aNode. parentNode;
Var bParentNode = bNode. parentNode;
// If both aNode and bNode have a parent node
If (aParentNode & bParentNode ){
AParentNode. replaceChild (bNode. cloneNode (true), aNode );
BParentNode. replaceChild (aNode, bNode );
}
}
</Script>
</Head>
<Body>
<P> Which city do you like? </P>
<Ul id = "city">
<Li id = "bj" name = "BeiJing"> BeiJing </li>
<Li> Shanghai </li>
<Li id = "dj"> Tokyo </li>
<Li> Seoul </li>
</Ul>
<Br>
<P> which single-host game do you like? </P>
<Ul id = "game">
<Li id = "rl"> Red Alert </li>
<Li> live </li>
<Li> need for speed </li>
<Li> World of Warcraft </li>
</Ul>
<Br>
Gender:
<Input type = "radio" name = "gender" value = "male"/> Male
<Input type = "radio" name = "gender" value = "female"/> Female
</Body>
</Html>
This article is from "change"