Dom
- 文档对象模型处理HTML和XML
- DOM树
- 文档:一个页面就是一个文档DOM中用document表示
- 元素:页面中所有标签都是元素,用element表示
- 节点:网页中所有内容都是节点(标签,属性,文本,注释等)用node表示
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pct98Lzx-1632658917126)(vx_images/5883945090954.png)] - DOM把以上内容都看做是对象。
获取元素
获取id元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="time">2019-9-9</div>
</body>
<script>
//因为文档页面从上往下加载,所以script写在标签下
//1. 根据id获取(getElementById)返回对象Object
var timer = document.getElementById("time");
console.log(timer);
console.log(typeof (timer));
//打印返回元素对象,更好查看属性和方法
console.dir(timer);
//2. 根据标签名获取
//3. 通过HTML5新增方法获取
//4. 特殊元素获取
</script>
</html>
获取标签名元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ol>
<li>111erw</li>
<li>222</li>
<li>333</li>
<li>444</li>
<li>555</li>
</ol>
<ol id="ol">
<li>滴滴答111</li>
<li>滴滴答222</li>
<li>滴滴答333</li>
<li>滴滴答444</li>
<li>滴滴答555</li>
</ol>
</body>
<script>
//1. 返回获取元素对象的集合,伪数组形式存储
// var lis = document.getElementsByTagName("li");
// console.log(lis);
// console.log(lis[0]);
//2. 遍历打印
// for (var i = 0; i < lis.length; i++) {
// console.log(lis[i]);
// }
//3. 如果页面只有一个li返回是伪数组
//4. 如果页面没有这个元素返回还是伪数组
//5.有多个ol获取元素(获取父元素)
// var ol = document.getElementsByTagName("ol");
// var lis1 = ol[0].getElementsByTagName("li");
// var lis2 = ol[1].getElementsByTagName("li");
// console.log(lis1);
// console.log(lis2);
// for (i = 0; i < lis1.length; i++) {
// console.log(lis1[i]);
// }
var ol = document.getElementById("ol").getElementsByTagName("li");
console.log(ol);
</script>
</html>
通过HTML5新增方法获取
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box">盒子1</div>
<div class="box">盒子2</div>
<div id="nav">
<ul>
<li>首页</li>
<li>产品</li>
</ul>
</div>
</body>
<script>
//1. getElementsByClassName根据类名获取元素集合
var boxs = document.getElementsByClassName("box");
console.log(boxs);
//2. 返回指定选择器的第一个元素对象
var firstBox = document.querySelector(".box");
console.log(firstBox); //返回盒子1
var firstBox1 = document.querySelector("#nav");
console.log(firstBox1); //返回#nav
var li = document.querySelector("li");
console.log(li); //返回第一个li
//3. 返回指定选择器的所有元素对象
var allBox = document.querySelectorAll(".box");
console.log(allBox);
var lis = document.querySelectorAll("li");
console.log(lis);
</script>
</html>
获取特殊元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//1. 获取body 元素
var body = document.body;
console.log(body);
console.dir(body);
console.log("--------------");
//2. 获取html元素
var htmlEle = document.documentElement;
console.log(htmlEle);
</script>
</body>
</html>
事件基础
概述
触发–相应机制
常见鼠标事件
鼠标事件 | 触发条件 |
---|
onclick | 鼠标点击左键触发 | onmouseover | 鼠标经过触发 | onmouseout | 鼠标离开触发 | onfocus | 获得鼠标焦点触发 | onblur | 失去鼠标焦点触发 | onmousemove | 鼠标移动触发 | onmouseup | 鼠标弹起触发 | onmousedown | 鼠标按下触发 |
操作元素
改变元素内容
element.innerText 不识别HTMl标签 去除空格换行
<body>
<button>显示当前系统时间</button>
<div>某个时间</div>
<script>
//1. 获取元素
var btn = document.querySelector("button");
var div = document.querySelector("div")
btn.onclick = function () {
div.innerText = "2021-09-14";
}
</script>
</body>
//获取时间时间
<button>显示当前系统时间</button>
<div>某个时间</div>
<p>123123</p>
<script>
//1. 获取元素
var btn = document.querySelector("button");
var div = document.querySelector("div")
btn.onclick = function () {
div.innerText = getTime();
};
function getTime() {
var date3 = new Date();
var year = date3.getFullYear();
var month = date3.getMonth() + 1;
var dates = date3.getDate();
var days = date3.getDay();
var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
return ("今天是:" + year + "年" + month + "月" + dates + "日\t" + arr[days]);
}
//元素不添加时间
var p = document.querySelector("p");
p.innerText = getTime();
element.innerHTML 可识别HTML标准推荐 保留空格换行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>
我是p标签
<span>我是span</span>
</p>
<div></div>
<script>
//1. innerText 不识别html标签 去除空格和换行
var div = document.querySelector("div");
div.innerText = "<strong>今天是:</strong>2019年";
//2 .innerHTML识别HTNL标签 保留空格换行
div.innerHTML = "<strong>今天是:</strong>2019年";
// 两个属性可以读写 可以获取元素中的内容
var p = document.querySelector("p");
console.log(p.innerText);
console.log(p.innerHTML);
</script>
</body>
</html>
属性操作
- 常用元素的属性操作
- innerText、innerHTML改变元素内容
- src、href
- id、alt、title
- onclick
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="ldh">刘德华</button>
<button id="zxy">张学友</button><br>
<img src="./images/ldh.jpg" alt="">
<script>
var ldh = document.getElementById("ldh");
var zxy = document.getElementById("zxy");
var p = document.querySelector("img");
zxy.onclick = function () {
p.src = "./images/zxy.jpg";
}
ldh.onclick = function () {
p.src = "./images/ldh.jpg";
}
</script>
</body>
</html>
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div
style="background-color: blue;color: white;width: 200px;height: 100px;text-align: center;font-size: 50px;line-height: 100px;">
</div>
<script>
var div = document.querySelector("div");
var nowTime = new Date();
var h = nowTime.getHours();
if (h < 10) {
div.innerHTML = "早上好";
} else if (h < 14) {
div.innerHTML = "中午好";
}
else if (h < 18) {
div.innerHTML = "下午好";
}
else if (h < 23) {
div.innerHTML = "晚上好";
}
else {
div.innerHTML = "深夜好梦";
}
</script>
</body>
</html>
表单元素的操作属性
可操作:type、value、checked、selected、disabled
- input修改值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <input type="text" name="" id="i1" value="请输入用户名"> -->
<button>按钮</button>
<input type="text" name="" id="i2" value="请输入内容">
<script>
//当鼠标聚焦文字消失
// var i1 = document.getElementById("i1");
// i1.onfocus = function () {
// i1.value = "";
// }
var btn = document.querySelector("button");
var i2 = document.getElementById("i2");
btn.onclick = function () {
i2.value = "被点击";
//点击之后按钮禁用
// btn.disabled = true;或者
this.disabled = true;
//this 指向当前函数的调用者
}
</script>
</body>
</html>
案例显示隐藏密码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 400px;
border-bottom: 1px solid #ccc;
margin: 100px auto;
position: relative;
}
.box input {
width: 370px;
height: 30px;
border: 0;
/* 聚焦时外边框消失 */
outline: none;
}
.box img {
width: 24px;
position: absolute;
right: 2px;
height: 30px;
}
</style>
</head>
<body>
<div class="box">
<label for="">
<img src="./images/close.png" alt="">
</label>
<input type="password">
</div>
<script>
var img = document.querySelector("img");
var i = document.querySelector("input");
var flag = 0;
img.onclick = function () {
if (!flag) {
i.type = "text";
img.src = "./images/open.png";
flag = 1
} else {
i.type = "password";
img.src = "./images/close.png";
flag = 0
}
}
</script>
</body>
</html>
样式属性操作
修改元素的大小、颜色、位置等样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
div {
width: 100px;
height: 100px;
border: 1px solid red;
background-color: #ccc;
}
</style>
<title>Document</title>
</head>
<body>
<div></div>
<script>
var d = document.querySelector("div");
d.onclick = function () {
// d.style里面的属性采用驼峰命名法
this.style.backgroundColor = "purple";
this.style.border = "2px solid pink";
}
</script>
</body>
</html>
点击图片消失
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<img src="./images/二维码.png" alt="">
</div>
<script>
var i = document.querySelector("img");
i.onclick = function () {
i.style.display = "none";
}
</script>
</body>
</html>
案例:循环精灵图背景
案例
案例:显示隐藏文本框内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
input {
color: #ccc;
margin: 100px auto;
display: block;
}
</style>
</head>
<body>
<input type="text" name="" id="" value="手机">
<script>
var text = document.querySelector("input");
//获得焦点时间onfocus
text.onfocus = function () {
if (this.value == '手机') {
this.value = "";
}
this.style.color = "#999";
}
text.onblur = function () {
if (this.value == "") {
this.value = "手机";
}
this.style.color = "#333"
}
</script>
</body>
</html>
使用className更改元素样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 300px;
background-color: wheat;
}
.change {
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div>文本</div>
<script>
//1. 使用element.style修改样式在样式少或者功能简单下使用
var text = document.querySelector("div");
// text.onclick = function () {
// text.style.backgroundColor = "purple";
// text.style.width = "100px";
// text.style.height = "100px";
// }
//2.element.className更改element的类名 用于复杂的情况 会覆盖原来的类名
//若想要软来的类名 可以加空格实现
text.onclick = function () {
text.className = "first change"
}
</script>
</body>
</html>
案例:密码提示框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 600px;
margin: 100px auto;
}
.message {
display: inline-block;
font-size: 12px;
color: #999;
padding-left: 20px;
}
.wrong {
color: red;
}
.reght {
color: green;
}
</style>
</head>
<body>
<div id="box">
<input type="password" class="ipt">
<p class="message">请输入6~12密码</p>
</div>
<script>
var ipt = document.querySelector(".ipt");
var message = document.querySelector(".message");
ipt.onblur = function () {
if (this.value.length < 6 || this.value.length > 12) {
message.className = "message wrong"
message.innerHTML = "您输入的位数不对"
} else {
message.className = "message right"
message.innerHTML = "输入正确"
}
}
</script>
</body>
</html>
总结
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Nm7nYmiX-1632658917128)(vx_images/254032249381.png)]
排他思想(算法)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<button>按钮5</button>
<script>
//1. 获取所有按钮元素
var btns = document.getElementsByTagName("button");
//2. btns得到伪数组
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function () {
//1. 咸把所有按钮的背景颜色去掉
for (var j = 0; j < btns.length; j++) {
btns[j].style.backgroundColor = "";
btns[j].style.color = "";
}
//2. 然后让点前元素背景颜色改成blacke
this.style.backgroundColor = "black";
this.style.color = "white";
}
}
</script>
</body>
</html>
案例
表格隔行变色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
border-collapse: collapse;
margin: 100px auto;
}
thead th {
background-color: cornflowerblue;
}
th {
text-align: center;
font-size: 15px;
height: 30px;
width: 100px;
}
tbody th {
font-weight: 400;
color: blue;
border-bottom: 1px solid #ccc;
}
.bg {
background-color: pink;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>代码</th>
<th>名称</th>
<th>最新公布经值</th>
<th>累计净值</th>
<th>请单位净值</th>
<th>净值增长率</th>
</tr>
</thead>
<tbody>
<tr>
<th>003500</th>
<th> suibain </th>
<th>22580</th>
<th>12345</th>
<th>12345</th>
<th>2.5</th>
</tr>
<tr>
<th>003500</th>
<th> suibain </th>
<th>22580</th>
<th>12345</th>
<th>12345</th>
<th>2.5</th>
</tr>
<tr>
<th>003500</th>
<th> suibain </th>
<th>22580</th>
<th>12345</th>
<th>12345</th>
<th>2.5</th>
</tr>
<tr>
<th>003500</th>
<th> suibain </th>
<th>22580</th>
<th>12345</th>
<th>12345</th>
<th>2.5</th>
</tr>
</tbody>
</table>
<script>
//1. 获取tbody的所有行
var trs = document.querySelector("tbody").querySelectorAll("tr");
//2. 利用循环 注册事件
for (var i = 0; i < trs.length; i++) {
//3. 鼠标经过时间
trs[i].onmouseover = function () {
this.className = "bg";
}
//4. 鼠标离开时间
trs[i].onmouseout = function () {
this.className = "";
}
}
</script>
</body>
</html>
表单全选取消全选
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
margin: 100px auto;
border-collapse: collapse;
}
th {
text-align: center;
line-height: 30px;
font-size: 15px;
width: 500px;
height: 30px;
border: 1px solid #ccc;
}
thead th {
background-color: blue;
color: white;
}
tbody th {
font-weight: 400;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th><input type="checkbox" id="thc"></th>
<th>商品</th>
<th>价钱</th>
</tr>
</thead>
<tbody>
<tr>
<th><input type="checkbox" id="tbc1"></th>
<th>iPhone8</th>
<th>8000</th>
</tr>
<tr>
<th><input type="checkbox" id="tbc2"></th>
<th>iPhone9</th>
<th>80000</th>
</tr>
<tr>
<th><input type="checkbox" id="tbc3"></th>
<th>iPhone10</th>
<th>80</th>
</tr>
<tr>
<th><input type="checkbox" id="tbc4"></th>
<th>iPhone22</th>
<th>800</th>
</tr>
</tbody>
</table>
<script>
//1. 全选和取消全选
var thc = document.getElementById("thc");
var tbcs = document.querySelector("tbody").querySelectorAll("input");
thc.onclick = function () {
for (var i = 0; i < tbcs.length; i++) {
tbcs[i].checked = this.checked;
}
}
//2. 复选按钮全选按钮
for (var i = 0; i < tbcs.length; i++) {
tbcs[i].onclick = function () {
var flag = true;
for (var j = 0; j < tbcs.length; j++) {
//tbcs[j].checked返回复选框的选择状态
if (!tbcs[j].checked) {
flag = false;
console.log(tbcs[j].checked);
}
}
//当checked=flase时 不选中 =true时选中
thc.checked = flag;
}
}
</script>
</body>
</html>
自定义属性的操作
- 获取属性这个
element.属性 获取属性值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="demo" index="1"></div>
<script>
var div = document.querySelector("div");
//1. 获取元素属性值
console.log(div.id);
//2. element.getAttribute("属性")
console.log(div.getAttribute("id"));
console.log(div.getAttribute("index"));
</script>
</body>
</html>
- 设置自定义元素属性值elements.setAttribute(“属性名”,“修改成属性值”)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="demo" index="1" class="na"></div>
<script>
var div = document.querySelector("div");
//1. 获取元素属性值
console.log(div.id);
//2. element.getAttribute("属性")
console.log(div.getAttribute("id"));
console.log(div.getAttribute("index"));
//3. 设置元素属性值
div.id = "text";
console.log(div.id);
div.className = "NAVAS";
console.log(div.className);
div.setAttribute("index", "www")
console.log(div.getAttribute("index"));
div.setAttribute("class", "naviNB")
console.log(div.getAttribute("class"));
</script>
</body>
</html>
- 移除属性值
div.removeAttribute("index");
tab切换案例(重点)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.tab {
border: 1px solid red;
}
#tab_list {
height: 39px;
}
#tab_list li {
float: left;
height: 39px;
line-height: 39px;
padding: 0 20px;
text-align: center;
cursor: pointer;
list-style: none;
}
#tab_list .current {
background-color: #c81623;
color: #fff;
}
.tab_con {
margin: 0 60px;
display: inline-block;
}
.item {
display: none;
}
</style>
</head>
<body>
<div class="tab">
<div id="tab_list">
<ul>
<li class="current">商品介绍</li>
<li>规格与包装</li>
<li>售后保障</li>
<li>商品评价</li>
<li>手机社区</li>
</ul>
</div>
<div class="tab_con">
<div class="item" style="display: block;">商品介绍模块</div>
<div class="item">规格与包装模块</div>
<div class="item">售后保障模块</div>
<div class="item">商品评价</div>
<div class="item">手机社区模块</div>
</div>
</div>
<script>
var lis = document.getElementById("tab_list").querySelectorAll("li");
var divs = document.querySelectorAll(".item");
for (var i = 0; i < lis.length; i++) {
//给5了小li设置编号
lis[i].setAttribute("index", i);
lis[i].onclick = function () {
//排他思想
for (var j = 0; j < lis.length; j++) {
divs[j].style.display = "";
lis[j].removeAttribute("class");
}
this.setAttribute("class", "current");
var index = this.getAttribute("index");
//下面的模块内容
divs[index].style.display = "block"
}
}
</script>
</body>
</html>
H5自定义属性
- 目的:为了保存并使用数据。有些数据可以保存到页面中二不用保存到数据库中。
- 自定义属性通过getAttribute(“属性”)获取
- H5新增属性:
1. 设置H5自定义属性
H5规定自定义属性data-开头作为属性名并赋值 如<div data-index="1"></div> 或者JS设置element.setAttribute(“data-index”,2)
2. 获取H5自定义属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="div" data-index="1" data-list-name="zcx"></div>
<script>
var div = document.getElementById("div");
//兼容获取自定义属性
console.log(div.getAttribute("data-index"));
//设置自定义属性值
div.setAttribute("data-index", "20");
console.log(div.getAttribute("data-index"));
//获取自定义属性H5新增
//datasets是一个集合存放了所有以data开头的自定义属性
console.log("------------------");
var index = div.dataset.index;
console.log(index);
console.log("------------------");
//或者
console.log(div.dataset["index"]);
//获取data-list-name
console.log(div.getAttribute("data-list-name"));
//或者
console.log(div.dataset.listName);
//或
console.log(div.dataset["listName"]);
</script>
</body>
</html>
节点操作
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r8tGotvx-1632658917129)(vx_images/1240200957.png)]
-
节点的描述
- 节点有nodeType(节点类型)、nodeName(节点名称)和nodeValue(节点值)三个基本属性
- 元素节点nodeType是1
- 属性节点nodeType是2
- 文本节点nodeType是33
- 实际开发中主要操作元素节点
-
节点层级
- 父级节点
node.parentNode
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="demo">
<div id="box">
<span id="erweima"></span>
</div>
</div>
<script>
//1. 父节点
var erweima = document.querySelector("#erweima");
var box = document.querySelector("#box");
console.log(box);
//得到里元素最近的父级节点 如果找不到父节点返回null
var box1 = erweima.parentNode;
console.log(box1);
</script>
</body>
</html>
子节点操作
获取子节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>我是div</div>
<span>我说span</span>
<ul>
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
<li>我是li4</li>
<li>我是li5</li>
</ul>
<ol>
<li>我是oli1</li>
<li>我是oli2</li>
<li>我是oli3</li>
<li>我是oli4</li>
<li>我是oli5</li>
</ol>
<div class="demo">
<div class="box">
<span class="erwerma">x</span>
</div>
</div>
<script>
//DOM提供的方法(API)获取
var ul = document.querySelector("ul");
var lis = ul.querySelectorAll("li");
//1. 子节点 childNodes(标准)包含所有节点 元素节点 文本节点
console.log(ul.childNodes);
//文本节点的nodeType是3
console.log(ul.childNodes[0].nodeType);
//元素节点的nodeType是1
console.log(ul.childNodes[1].nodeType);
//拿出所有元素节点
for (var i = 0; i < ul.childNodes.length; i++) {
if (ul.childNodes[i].nodeType == 1) {
console.log(ul.childNodes[i]);
}
}
console.log("----------------------");
//不提倡使用childNodes
//2. children(非标准)打印所有元素节点(常用)
console.log(ul.children);
</script>
</body>
</html>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZvmUdelg-1632658917131)(vx_images/3132815110964.png)]
获取第一个和最后一个节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ol>
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
<li>我是li4</li>
<li>我是li5</li>
</ol>
<script>
var ol = document.querySelector("ol");
//firstChild获取第一个子节点 无论文本节点或者元素节点
console.log(ol.firstChild);
console.log(ol.lastChild);
//firstElementChild返回第一个子元素节点
console.log(ol.firstElementChild);
console.log(ol.lastElementChild);
//IE9以上支持
console.log("--------------------");
//实际开发 既没有兼容问题又返回元素
console.log(ol.children[0]);
console.log(ol.children[ol.children.length - 1]);
</script>
</body>
</html>
案例下拉菜单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
li {
/* 无序列表取消标记 */
list-style-type: none;
}
a {
/* //下划线 */
text-decoration: none;
font-size: 14px;
}
.nav {
margin: 100px;
}
.nav>li {
position: relative;
float: left;
width: 80px;
height: 41px;
text-align: center;
}
.nav li a {
display: block;
width: 100%;
height: 100%;
line-height: 41px;
color: #333;
}
.nav>li>a:hover {
background-color: #eee;
}
.nav ul {
display: none;
position: absolute;
top: 41px;
left: 0;
width: 100%;
border-left: 1px solid #FECC5B;
border-right: 1px solid #FECC5B;
}
.nav ul li {
border-bottom: 1px solid #FECC5B;
}
.nav ul li a:hover {
background-color: #FFF5DA;
}
</style>
</head>
<body>
<ul class="nav">
<li>
<a href="#">微博</a>
<ul>
<li>
<a href="">私信</a>
</li>
<li>
<a href="">评论</a>
</li>
<li>
<a href="">@我</a>
</li>
</ul>
</li>
<li>
<a href="#">微博</a>
<ul>
<li>
<a href="">私信</a>
</li>
<li>
<a href="">评论</a>
</li>
<li>
<a href="">@我</a>
</li>
</ul>
</li>
<li>
<a href="#">微博</a>
<ul>
<li>
<a href="">私信</a>
</li>
<li>
<a href="">评论</a>
</li>
<li>
<a href="">@我</a>
</li>
</ul>
</li>
<li>
<a href="#">微博</a>
<ul>
<li>
<a href="">私信</a>
</li>
<li>
<a href="">评论</a>
</li>
<li>
<a href="">@我</a>
</li>
</ul>
</li>
</ul>
<script>
var nav = document.querySelector(".nav");
var lis = nav.children;//得到4个小li
//循环注册事件
for (var i = 0; i < lis.length; i++) {
lis[i].onmouseover = function () {
this.children[1].style.display = "block";
}
lis[i].onmouseout = function () {
this.children[1].style.display = "none";
}
}
</script>
</body>
</html>
兄弟节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>div</div>
<span>asd
</span>
<script>
var div = document.querySelector("div");
//获取下一个兄弟节点 包含元素和文本等
console.log(div.nextSibling);
//获取下一个兄弟元素节点 ie9以上
console.log(div.nextElementSibling);
console.log("------------------");
//获取上一个兄弟节点 包含文本节点等
console.log(div.previousSibling);
//获取上一个兄弟元素节点 若没有返回null ie9以上
console.log(div.previousElementSibling);
//解决兼容性 封装函数
function getNextElementSibling(element) {
var el = element;
while (el = el.nextSibling) {
if (el.nodeType == 1) {
return el;
}
}
return null;
}
console.log("---------------------");
console.log(getNextElementSibling(div));
</script>
</body>
</html>
创建节点
例如 发表评论 动态创建元素节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>123</li>
</ul>
<script>
//1. 创建li元素节点
var li = document.createElement("li");
//2. 将li节点添加到ul
var ul = document.querySelector("ul");
//a. 将li放入ul的子节点末尾
ul.appendChild(li);
//b. 指定位置插入,父节点指定子元素前面
//3. node.insertBefore(child,指定元素)
var lili = document.createElement("li");
ul.insertBefore(lili, ul.children[0]);
//4. 页面添加新的元素步骤:1. 创建元素,2. 添加元素
</script>
</body>
</html>
案例留言板
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rAwfvsWL-1632658917132)(vx_images/363548139390.png)]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
padding: 100px;
}
textarea {
width: 200px;
height: 100px;
border: 1px solid pink;
outline: none;
resize: none;
}
ul {
margin-top: 50px;
}
li {
width: 300px;
padding: 5px;
background-color: rgb(245, 209, 243);
color: red;
font-size: 14px;
margin: 15px 0;
}
</style>
</head>
<body>
<textarea name="" id="" cols="30" rows="10">123</textarea>
<button>发布</button>
<ul></ul>
<script>
//1. 获取元素
var btn = document.querySelector("button");
var text = document.querySelector("textarea");
var ul = document.querySelector("ul");
//2. 注册事件
btn.onclick = function () {
if (text.value == "") {
alert("请输入内容")
return false;
} else {
//(1) 创建元素
var li = document.createElement("li");
//赋值
li.innerText = text.value;
//(2) 放入元素(最后一行)
// ul.appendChild(li);
//放在第一行
ul.insertBefore(li, ul.children[0]);
}
}
</script>
</body>
</html>
删除节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>删除</button>
<ul>
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
<li>我是li4</li>
<li>我是li5</li>
</ul>
<script>
var ul = document.querySelector("ul");
var btn = document.querySelector("button");
//删除li2
// ul.removeChild(ul.children[1]);
//点击按钮依次删除
btn.onclick = function () {
if (ul.children.length == 0) {
this.disabled = true;
} else {
ul.removeChild(ul.children[0]);
}
}
</script>
</body>
</html>
删除留言板
阻值a链接跳转
<a href = 'javascript:;'>删除</a> 或者<a href = 'javascript:void(0);'>删除</a>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
padding: 100px;
}
textarea {
width: 200px;
height: 100px;
border: 1px solid pink;
outline: none;
resize: none;
}
ul {
margin-top: 50px;
}
li {
width: 300px;
padding: 5px;
background-color: rgb(245, 209, 243);
color: red;
font-size: 14px;
margin: 15px 0;
}
li a {
float: right;
}
</style>
</head>
<body>
<textarea name="" id="" cols="30" rows="10">123</textarea>
<button>发布</button>
<ul></ul>
<script>
//1. 获取元素
var btn = document.querySelector("button");
var text = document.querySelector("textarea");
var ul = document.querySelector("ul");
//2. 注册事件
btn.onclick = function () {
if (text.value == "") {
alert("请输入内容")
return false;
} else {
//(1) 创建元素
var li = document.createElement("li");
//赋值
li.innerHTML = text.value + "<a href = 'javascript:;'>删除</a>";
//(2) 放入元素(最后一行)
// ul.appendChild(li);
//放在第一行
ul.insertBefore(li, ul.children[0]);
//删除
//(3)删除元素 删除当前元素的li a的父亲
var as = document.querySelectorAll("a");
for (var i = 0; i < as.length; i++) {
as[i].onclick = function () {
//删除 li父节点下的当前li节点
ul.removeChild(this.parentNode)
}
}
}
}
</script>
</body>
</html>
赋值节点
node.cloneNode() 参数为空或者false则值克隆节点本身,不可隆子节点及内部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
<li>li4</li>
<li>li5</li>
</ul>
<script>
var ul = document.querySelector('ul');
//1. node.cloneNode(参数);
var li0 = ul.children[0].cloneNode(1);
ul.appendChild(li0);
</script>
</body>
</html>
案例 动态生成表格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
width: 500px;
margin: 100px auto;
border-collapse: collapse;
text-align: center;
}
td,
th {
border: 1px solid #333;
}
thead tr {
height: 40px;
background-color: #ccc;
}
</style>
</head>
<body>
<table cellspacing="0">
<thead>
<tr>
<th>姓名</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
// 1.先去准备好学生的数据
var datas = [{
name: '魏璎珞',
subject: 'JavaScript',
score: 100
}, {
name: '弘历',
subject: 'JavaScript',
score: 98
}, {
name: '傅恒',
subject: 'JavaScript',
score: 99
}, {
name: '明玉',
subject: 'JavaScript',
score: 88
}, {
name: '大猪蹄子',
subject: 'JavaScript',
score: 0
}];
//往tbody里创建行
var tbody = document.querySelector("tbody");
for (var i = 0; i < datas.length; i++) {
var tr = document.createElement("tr");
tbody.appendChild(tr);
//往tr里添加td
for (var k in datas[i]) {
var td = document.createElement("td");
//将值(数据)给td
td.innerText = datas[i][k];
tr.appendChild(td)
}
//创建有删除两个字的单元格
var td = document.createElement("td");
td.innerHTML = "<a href = 'javascript:;'>删除</a>"
tr.appendChild(td);
}
//4. 删除操作
var as = document.querySelectorAll("a");
console.log(as);
for (var i = 0; i < as.length; i++) {
as[i].onclick = function () {
//删除 a 所在的行(连接得爸爸的爸爸) node.removeChild(child);
tbody.removeChild(this.parentNode.parentNode)
}
}
</script>
</body>
</html>
三种动态创建元素的区别
- document.write()
- element.innerHTML
- document.createElement()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>点击</button>
<p>
abc
</p>
<div class="inner"></div>
<div class="create"></div>
<script>
//三种创建元素的范式
// 1. document.write() 如果页面加载完毕 在执行会重绘页面
var btn = document.querySelector("button");
btn.onclick = function () {
document.write("<div>123123</div>")
}
// 2. element.innerHTML
var inner = document.querySelector(".inner");
for (var i = 0; i <= 100; i++) {
inner.innerHTML += '<a href="javascript:;">百度</a>'
}
// inner.innerHTML = '<a href = "javascript:;">百度</a>'
// 3. document.createElement()
var create = document.querySelector(".create");
for (var i = 0; i < 100; i++) {
var a = document.createElement("a");
create.appendChild(a)
}
</script>
</body>
</html>
区别:
- document.write()是直接将内容写入页面内容流,但是文档流执行完毕,则他会导致页面全部重绘
// 1. document.write()
var btn = document.querySelector("button");
btn.onclick = function () {
document.write("<div>123123</div>")
}
//当点击按钮时,页面只剩<div>123123</div>
- element.innerHTML:将内容写入某个DOM节点不会导致页面全部重绘
- element.innerHTML:创建多个元素效率更高(蚕蛹数组形式拼接),结构复杂
- document.createElement():创建多个元素效率稍低,但是结构清晰
|