JavaScript DOMプログラミング学習ノート-ノード挿入
3037 ワード
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Document</title>
<script type="text/javascript">
// insertBefore ,
window.onload = function() {
var cityNode = document.getElementById("city");
var bjNode = document.getElementById("bj");
var xyjNode = document.getElementById("xyj");
//cityNode.insertBefore(rlNode, bjNode)
var szNode = document.getElementById("sz");
insertAfter(xyjNode, szNode);
}
// newNode refNode .W3C 。
function insertAfter(newNode, refNode) {
// refNode 。
var parentNode = refNode.parentNode;
if (parentNode) {
var lastNode = parentNode.lastChild;
if (refNode == lastNode) {
// , newNode refNode ,appendChild
parentNode.appenChild(newNode);
} else {
// , refNode ,
var nextNode = refNode.nextSibling;
parentNode.insertBefore(newNode, nextNode);
}
}
}
</script>
</head>
<body>
<p> ?</p>
<ul id="city">
<li id="bj" name="beijing"> </li>
<li id="sh"> </li>
<li id="sz"> </li>
<li id="sz2"> 2</li>
</ul>
<p> ?</p>
<ul id="book">
<li id="xyj" name="xyj"> </li>
<li> </li>
<li> </li>
<li> 2</li>
</ul>
</html>
innerHTMLはDOM標準ではありませんが、すべてのブラウザがサポートされています.<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Document</title>
<script type="text/javascript">
// innerHTML
window.onload = function() {
var cityNode = document.getElementById("city");
//alert(cityNode.innerHTML);
// city book
var tempHTML = cityNode.innerHTML;
var bookNode = document.getElementById("book");
cityNode.innerHTML = bookNode.innerHTML;
bookNode.innerHTML = tempHTML;
}
</script>
</head>
<body>
<p> ?</p>
<ul id="city">
<li id="bj" name="beijing"> </li>
<li id="sh"> </li>
<li id="sz"> </li>
<li id="sz2"> 2</li>
</ul>
<p> ?</p>
<ul id="book">
<li id="xyj" name="xyj"> </li>
<li> </li>
<li> </li>
<li> 2</li>
</ul>
</html>