刚学的JS对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=GBK" />
<title></title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
/**
//在div中添加子节点
//为div1添加段落2,位置:最后
var p2 = document.createElement("p"); //创建p元素节点
p2.setAttribute("id","p2");//添加id属性
var txNode = document.createTextNode("段落2");//创建文本节点
p2.appendChild(txNode);//将文本节点添加到p2元素节点中
//将p3添加到div中,作为div的最后一个子节点
document.getElementById("div1").appendChild(p3);
*/
/*
//为div1添加段落,位置:前面,中间
var p0=document.createElement("p");
var txNode0=document.createTextNode("段落0");
p0.setAttribute("id","p0");
p0.appendChild(txNode0);
var p2=document.createElement("p");
var txNode2=document.createTextNode("段落2");
p2.setAttribute("id","p2");
p2.appendChild(txNode2);
//将p0添加到div的最前面,p2添加到中间
document.getElementById("div1").insertBefore(p0,document.getElementById("p1"));//p1之前
document.getElementById("div1").insertBefore(p2,document.getElementById("p3"));//p3之前
*/
/*
//在body中添加子节点 位置:最后
var div3 = document.createElement("div");
div3.setAttribute("id","div3");
var p7 = document.createElement("p");
p7.setAttribute("id","p7");
var txNo7=document.createTextNode("段落7");
p7.appendChild(txNo7);
var p8 = document.createElement("p");
p8.setAttribute("id","p8");
var txNo8=document.createTextNode("段落8");
p8.appendChild(txNo8);
div3.appendChild(p7);
div3.appendChild(p8);
document.body.appendChild(div3);
*/
/*
//在body中添加子节点 位置:开始、中间
var div3 = document.createElement("div");
div3.setAttribute("id","div3");
var p7 = document.createElement("p");
p7.setAttribute("id","p7");
var txNo7=document.createTextNode("段落7");
p7.appendChild(txNo7);
var p8 = document.createElement("p");
p8.setAttribute("id","p8");
var txNo8=document.createTextNode("段落8");
p8.appendChild(txNo8);
div3.appendChild(p7);
div3.appendChild(p8);
var p10=document.createElement("p");
var txNode10=document.createTextNode("段落10");
p10.appendChild(txNode10);
document.body.insertBefore(p10,document.getElementById("div1"));//添加在div1之前
document.body.insertBefore(div3,document.getElementById("div2"));//添加在div2之前
*/
/*
//删除段落5:必须提供父元素
var div2=document.getElementById("div2");
var p5=document.getElementById("p5");
div2.removeChild(p5);
// p5.parentNode.removeChild(p5);
*/
//替换段落5:
var reP=document.createElement("p");
var txNodeRe=document.createTextNode("替换段落");
reP.setAttribute("id","rep");
reP.appendChild(txNodeRe);
document.getElementById("div2").replaceChild(reP,document.getElementById("p5"));
});
</script>
<style>
</style>
</head>
<body>
<div id="div1">
<p id="p1">段落1</p>
<p id="p3">段落3</p>
</div>
<div id="div2">
<p id="p4">段落4</p>
<p id="p5">段落5</p>
</div>
</body>
</html>