<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dom</title>
</head>
<body id="gbd">
<div id="id1"><p id="p1">锄禾日当午</p></div>
<div id="id2"><p>窗前明月光</p><p>疑是地上霜</p></div>
<div id="id3"><p id="p11">春眠不觉晓</p><p id="p12">处处闻啼鸟</p></div>
<button οnclick="test()">切换</button>
<script>
var id1 = document.getElementById('id1');
var newnode = document.createElement('h2');
newnode.innerHTML = "汗滴禾下土";
id1.appendChild(newnode);
var p1 = document.getElementById('p1');
var newnode2 = document.createElement('h3');
newnode2.innerHTML = '悯农';
//inserBefore必须有两个参数,第一个是要插入的节点,第二个是节点的位置
id1.insertBefore(newnode2,p1);
var id2 = document.getElementById('id2');
var rem = id2.removeChild(id2.childNodes[1]);
document.write('删除的节点是:'+id2.childNodes[1])
document.write('删除的节点是:'+rem)
console.log(rem)
document.write(rem.innerHTML);
//createTextNode创建文本节点
var h1 = document.createElement('h1');
var h1text = document.createTextNode('我们都是路人甲乙丙丁');
h1.appendChild(h1text);
var gbd = document.getElementById('gbd');
gbd.appendChild(h1);
console.log(document.body)
//replaceChild(),两个参数必须。第一个节点取代第二个节点。子节点替换
function test(){
var p11 = document.getElementById('p11');
//var p12 = document.getElementById('p12');
var id3 = document.getElementById('id3');
var p12 = id3.childNodes[1];
var h11 = document.createElement('h1');
var h11text = document.createTextNode('花花世界,鸳鸯蝴蝶');
h11.appendChild(h11text)
//id3.appendChild(h11);
console.log(id3)
p11.parentNode.replaceChild(h11,p12)
}
</script>
</body>
</html>
DOM常见举例
最新推荐文章于 2022-08-05 02:31:30 发布