五 DOM相关
5.1 DOM操作获取节点
<div id="box1">
<p id="p1">段落</p>
</div>
<div id="box2">
<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'
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>
5.2 操作添加节点
<script>
document.write('<span>aaaa</span>')
</script>
<div id="div1">
<p id="p1">段落</p>
</div>
<script>
document.write('<span>aaaa</span>')
</script>
<script>
a = document.createElement('a')
p = document.getElementById('p1')
div1 = document.getElementById('div1')
.insertBefore(a,p)
</script>
5.3DOM操作删除节点
<body>
<p id="p1">段落1</p>
<p>段落2</p>
<p>段落3</p>
</body>
<script>
// remove() - 删除节点
// 节点.remove()
p1 = document.getElementById('p1')
p1.remove()
p = document.getElementsByTagName('p')
console.log(p)
p[1].remove()
5.4 DOM操作向节点中添加内容和属性
<body>
<a class="a1">百度<b>一下</b></a>
<script>
a1 = document.getElementsByTagName('a')
a1[0].innerHTML = 'HTML<b>CSS</b>'
a1[0].href = 'https://www.baidu.com'
a1[0].target = '_blank'
</script>
</body>
5.5 js操作浏览器
<script>
function openwindow1(){
w1 = window.open('https://www.baidu.com')
}
function close1(){
w1.close()
}
function openwindow2(){
w2 = window.open('https://www.baidu.com','_blank','width=1200,height=800')
}
function close2(){
w2.close()
}
function close3(){
window.close()
}
function to_bottom(){
y = 0
y_max = 5000
while(y <= y_max){
y += 500
window.scrollTo(0,y)
}
}
</script>
<input type="submit" value="打开新窗口" onclick="openwindow2()">
<input type="submit" value="关闭新窗口" onclick="close2()">
<br>
<input type="submit" value="打开新标签页" onclick="openwindow1()">
<input type="submit" value="关闭标签页" onclick="close1()">
<br>
<input type="submit" value="关闭当前窗口" onclick="close3()">
<input type="submit" value="滚动到页面底部" onclick="to_bottom()">
<div style="height: 5000px;"></div>
<p>页面底部</p>