4.dom操作
createElement 创建一个元素
<button id="btn">点击</button>
<ul id="ul1"></ul>
<script>
var oBtn = document.getElementById("btn")
var oUl = document.getElementById("ul1")
oBtn.onclick = function(){
var oLi = document.createElement("li")
oLi.innerHTML = "nodeing.com"
console.log(oLi)
}
</script>
appendChild() 在最后添加一个子元素
<button id="btn">点击</button>
<ul id="ul1"></ul>
<script>
var oBtn = document.getElementById("btn")
var oUl = document.getElementById("ul1")
num = 0
oBtn.onclick = function(){
num++
var oLi = document.createElement("li")
oLi.innerHTML = "nodeing.com" + num
oUl.appendChild(oLi)
}
</script>
insertBefore() 在某个元素之前插入一个子元素
<button id="btn">点击</button>
<ul id="ul1">
<li id="first">11111</li>
</ul>
<script>
var oBtn = document.getElementById("btn")
var oUl = document.getElementById("ul1")
var oFirst = document.getElementById("first")
num = 0
oBtn.onclick = function(){
num++
var oLi = document.createElement("li")
oLi.innerHTML = "nodeing.com" + num
oUl.insertBefore(oLi, oFirst)
oFirst = oLi
}
</script>
removeChild() 删除某个子元素
<button id="btn">点击</button>
<ul id="ul1">
<li id="first">11111</li>
</ul>
<script>
var oBtn = document.getElementById("btn")
var oUl = document.getElementById("ul1")
var oFirst = document.getElementById("first")
num = 0
oBtn.onclick = function(){
num++
var oLi = document.createElement("li")
oLi.innerHTML = "nodeing.com" + num
oUl.insertBefore(oLi, oFirst)
oFirst = oLi
}
oUl.onclick = function(ev){
var ev = ev || event
this.removeChild(ev.target)
}
</script>
getAttribute/setAttribute
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box{
width: 100px;
height: 100px;
background-color: royalblue
}
</style>
</head>
<body>
<div id="box">nodeing.com</div>
<script>
var oBox = document.getElementById("box")
alert(oBox.getAttribute("id"))
document.onclick = function(){
oBox.setAttribute("class", "box")
}
</script>
</body>
</html>
网友评论