DOM的相关属性

107 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table{
width: 100%;
border-collapse: collapse;
}
td{
border: 1px solid darkgoldenrod;
width: 100px;
text-align: center;
padding: 20px 0;
}
</style>
</head>
<body>
<div id="app">
<div class="demon">
111111
</div>
</div>
<div class="demon">
22222222222
</div>
<table class="tb zz">
<tr></tr>
</table>
<script>
//getElementsByClassName 获取所有指定类名的元素
//document.getElementsByName 可返回带有指定名称的对象的集合
//document.getElementsByTagName 可返回带有指定标签名的对象的集合
//document.getElementById 返回对拥有指定 ID 的第一个对象的引用
// let app=document.getElementById("app")
// console.log(app.getElementsByClassName('demon'));
// let demon=document.getElementsByTagName('demon')
// console.log(demon);
let app=document.getElementById('app')
console.log(app.children);//获取 body 元素的子元素集合
console.log(app.parentElement);//获取对象层次中的父对象
console.log(app.nextElementSibling);//返回下一个列表选项的 HTML 内容
console.log(app.previousElementSibling);//返回上一个列表选项的 HTML 内容
let table=document.createElement('table')//通过指定名称创建一个元素
for (let i = 1; i < 6; i++) {
let tr=document.createElement('tr')
table.appendChild(tr)
for (let j = 1; j < 6; j++) {
let td=document.createElement('td')
td.innerHTML=i*j
// 点击高亮
td.onclick=function(){
let tds=document.getElementsByTagName('td')
for (let i = 0; i < tds.length; i++) {
tds[i].style.color="#000"
tds[i].style.fontSize="16px"
}
this.style.color="#f00"
this.style.fontSize="20px"
}
tr.appendChild(td)
}
}
table.classList.add('td')
table.classList.add('zz')
// 第一行第一个
table.firstElementChild.firstElementChild.style.background='red'
table.firstElementChild.firstElementChild.style.color='#fff'
// 第一行最后一个
table.firstElementChild.lastElementChild.style.background='green'
table.firstElementChild.firstElementChild.style.color='#fff'
// 最后一行第一个
table.lastElementChild.firstElementChild.style.background='orange'
table.lastElementChild.firstElementChild.style.color='#fff'
// 最后一行最后一个
table.lastElementChild.lastElementChild.style.background='purple'
table.lastElementChild.lastElementChild.style.color='#fff'
// 最后一行的上一行的最后一个
table.lastElementChild.previousElementSibling.lastElementChild.style.background='skyblue'
table.lastElementChild.previousElementSibling.lastElementChild.style.color='#fff'
document.body.appendChild(table)
</script>
</body>
</html>