appendChild() 方法在指定元素节点的最后一个子节点之后添加节点。
该方法返回新的子节点。
注意:
appendChild()方法通常与document.createElement("div")或document.getElementById("id")函数同用,表示先创建然后再添加。
appendChild()的参数不是字符串而是一个对象。
如 nDiv = document.createElement("div");document.body.appendChild(nDiv);这个nDiv是没有引号的,是个div对象。
html
<!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>appendChild</title>
<style>
div{ background:#0000FF;width:100px;height:100px;}
span{ background:#00FF00;width:100px;height:100px;}
p{ background:#FF0000;width:100px;height:100px;}
</style>
</head>
<body>
<div id="a"><span>SPAN</span>DIV</div>
<span>SPAN</span>
<p>P</p>
<button type="button" onclick=cloneX()>创建新节点</button>
</body>
</html>
js
function cloneX(){
var nDiv = document.createElement("div"); //创建之后必须通过appendChild()之类的函数才能在页面上显示
document.body.appendChild(nDiv); //不能用document.appendChild,必须用document.body.appendChild();
//var txt = document.createElement("input");
try{
var txt = document.createElement("<input name='bobo' />")
//只有IE可以看到,FF会进行catch(e).这种写法对IE和FF的差别属性很有用,如现在这个name属性,如果用下面FF这种写法,IE不认,所以IE要用上面的写法,其他通用属性可以用下面的写法。
}
catch(e){
var txt = document.createElement("input") //FF通过这种方式做到与IE一样,IE也可以直接用这种方式。
txt.name = 'bobo';
}
txt.style.margin = 10+'px';
txt.value = "bobowa";
nDiv.appendChild(txt);
b = document.getElementsByName("bobo")[0];
alert(b.value)
}
FF怎么获得类似IE,outHTML
html
<!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=gb2312" />
<title>获取outerHMTL</title>
<style>
div{ background:#0000FF;width:100px;height:100px;}
span{ background:#00FF00;width:100px;height:100px;}
p{ background:#FF0000;width:100px;height:100px;}
</style>
</head>
<body>
<div id="a"><span>SPAN</span>DIV</div>
<span>SPAN</span>
<p>P</p>
</body>
</html>
js
function getOuterHTML(id){
var el = document.getElementById(id);
var newNode = document.createElement("div");
//document.appendChild(newNode);
document.body.appendChild(newNode);
var clone = el.cloneNode(true);
newNode.appendChild(clone);
alert(newNode.innerHTML);
document.body.removeChild(newNode);
}
getOuterHTML("a");