js_DOM节点的增删改查与属性设置

1、DOM节点的增删改
增加标签:appendChild
删除标签:removeChild
修改标签:replaceChild

2、添加CSS样式:
p_ele.style.color="red";



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>

<style>
.v1,.v2,.v3{
width: 300px;
height: auto;
}
.v1{
background-color: #2459a2;
}
.v2{
background-color: red;
}
.v3{
background-color: deepskyblue;
}
</style>


</head>
<body>


<div class="v1">
<button class="but1">增</button>
div1
</div>
<div class="v2">
<button class="but2">删</button>
div2</div>
<div class="v3">
<button class="but3">改</button>
div3
<p>hello v3</p>
</div>


</body>
<script>


var add_ele=document.getElementsByClassName("but1")[0];
var v1_ele=document.getElementsByClassName("v1")[0];
//<!-- 插入新的标签appendChild与内容-->
add_ele.onclick=function () {
//创建P标签
var p_ele=document.createElement("p");
//写入内容
p_ele.innerHTML="hello p";
    // 添加css样式
     p_ele.style.color="red";

//在<div class="v1">下插入P标签
v1_ele.appendChild(p_ele);

};

// 删除标签 removeChild
var del_ele=document.getElementsByClassName("but2")[0];
var sons=v1_ele.getElementsByTagName("p");
del_ele.onclick=function () {
if(sons.length!=0){
v1_ele.removeChild(sons[0])
}
}

// 修改标签 replaceChild
var up_ele=document.getElementsByClassName("but3")[0];
var v3_ele=document.getElementsByClassName("v3")[0];
up_ele.onclick=function () {
var p_ele=v3_ele.getElementsByTagName("p")[0];
var img_ele=document.createElement("img");
img_ele.src="2.jpg";
//标签替换
if(p_ele!=undefined){
v3_ele.replaceChild(img_ele,p_ele)
}
}

</script>

</html>

js_DOM节点的增删改查与属性设置

上一篇:jQuery之onload与ready


下一篇:request.getRequestDispatcher("**.jsp").forward(request,response);乱码的解决