javascript中有很简便的添加子节点的方法,但是没有直接添加父节点的方法,可以通过变通的方法实现。
思路:创建一个需要添加为的父节点,不直接添加成子节点的父节点,而是把这个父节点添加成body的子节点,然后把子节点添加成父节点的子节点。
例子:给子节点son,添加一个父节点father.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>添加父节点</title>
</head>
<body>
<div style="background-color:#F00;width:50px;height:50px;" id="son"> </div>
<script>
var son=document.getElementById("son");
var father=document.createElement("div");
father.style.width="200px";
father.style.height="100px";
father.style.backgroundColor="silver";
document.body.appendChild(father);
father.appendChild(son);
</script>
</body>
</html>