DOM操作获取节点
DOM(document object model) 操作
js提供了一个document,指向的是html,在js中通过document对象 可以直接或者间接获取页面内容对应的标签。
DOM操作具体内容 - 操作节点(节点就是标签)
a.直接获取节点 - document.getElementId(id属性值) - 通过id属性值获取标签
getElementByClassName(class属性值)
getElementsByName(标签名)
b.获取父节点:节点.parentElement - 获取指定节点的父节点
c.获取子节点:节点.children - 获取指定节点的所有子节点
节点.firstElementchild - 获取指定节点的第一个子节点
节点.lastElementchild - 获取指定节点的最后一个子节点
d.添加节点
e.删除节点
<body>
<div id = "box1">
<p id = "p1">段落</p>
</div>
<div id = "box3">
<a href="">百度</a>
<p id = "p2">段落</p>
</div>
<div id = "box3">
<p id = "p3">段落</p>
</div>
<script type="text/javascript">
p1 = document.getElementById('p1')
console.log(p1)
p1.style.color = 'red'
//p1.style = 'color:red;'
p2 = document.getElementsByTagName('p')
console.log(p2)
colors = ['blue','green','pink']
for(x in p2){
p2[x].style = `color:${colors[x]};`
}
div1 = document.getElementById('p1').parentElement
console.log(div1)
</script>
</body>
DOM操作添加节点
1.创建新的节点
document.createElement(标签名)
2.添加节点
节点1.appendChild(节点2) - 在节点1的最后添加节点2(节点1和节点2是父子)
节点2.insertBefore(节点2,节点3) = 在节点1中节点3的前边添加节点2
<body>
<script>
document.write('<span>aaaa</span>')
</script>
<div id = "div1">
<p>段落</p>
</div>
<script>
//直接向body标签添加子标签
document.write('<span>aaaa</span>')
</script>
<script>
//向P标签前添加新标签
a = document.createElement('a')
p = document.getElementById('p1')
div1 = document.getElementById('div1')
.insertBefore(a,p)
</script>
</body>
DOM操作删除节点
<body>
<p id= "p1">段落1</p>
<p>段落2</p>
<p>段落3</p>
</body>
<script>
//remove() - 删除节点
//节点.remove()
p1 = document.getElementById('p1')
p1.remove()
p = document.getElementsByName('p')
console.log(p)
p[1].remove()
</script>
DOM操作向节点中添加内容和属性
节点.innerText – 标签内部的文字(子标签也属于文字)
节点.innerHTML – 标签内部的文字(包括子标签内部的文字)
<body>
<a class = "a1">百度<b>一下</b></a>
<script>
a1 = document.getElementsByTagName('a')
//a1[0].innerText = 'HTML'
//a1[0].innerText = 'HTML<b>CSS</b>'
//a1[0].innerHTML = 'HTML'
a1[0].innerHTML = 'HTML<b>CSS</b>'
//节点.属性 = 属性值 ---> 向节点内添加或修改属性
a1[0].href = 'http://www.baidu.com'
a1[0].target = '_blank'
a1[0].className = 'a2'
</script>
</body>
js操作浏览器
-
打开关闭标签页
//打开浏览器新标签页:window.open() function openwindow1(){ w1 = window.open('https://www.baidu.com') } //关闭刚打开的新标签页 function close1(){ w1.close() } <input type="submit" value="打开新窗口" onclick="openwindow2()"> <input type="submit" value="关闭窗口" onclick="close2()">
-
打开关闭窗口
//打开新窗口 function openwindow2(){ w2 = window.open('https://www.baidu.com','_blank','width=800,height=800') w2.moveTo(500,200) } function close2(){ w2.close() } //关掉当前窗口 function close3(){ window.close() } <input type="submit" value="打开新标签页" onclick="openwindow1()"> <input type="submit" value="关闭标签页" onclick="close1()"> <input type="submit" value="关闭当前窗口" onclick="close3()">
-
页面滚动
//页面滚动 function to_bottom(){ //window.scrollTo(x,y) y = 0 y_max = 5000 while(y <= y_max){ y += 500 window.scrollTo(0,y) } } <input type="submit" value="滚动到页面底部" onclick="to_bottom()"> <div style="height:5000px;"></div> <p>页面底部</p>