DOM
浏览器的网页就是一个DOM节点树
核心
查找
添加
删除
获取Dom节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script>-->
<!-- alert("hello javascript")-->
<!-- </script>-->
</head>
<body>
<div id="father">
<h1 id="h"></h1>
<p class="p1"></p>
<ul></ul>
</div>
<script>
"use strict";
let h=document.getElementById("h");
let p=document.getElementsByClassName("p1");
let ul=document.getElementsByTagName("ul");
let father=document.getElementById("father");
let children = father.children;//获取所有子节点
//father.firstchild
//father.lastchild
</script>
</body>
</html>
更新节点
更新文本
h.innerText=123
h.innerHTML="<strong>456</strong>"
innerHTML可以识别html标签
更新css
var ss=document.getElementById("su")
su.style.color="red";
su.style.padding="20px";//属性值用字符串包裹
su.style.fontSize="20px";//_转驼峰命名
删除DOM节点
先获取父节点,再通过父节点删除
father.removechild("p1");
father.removeChild(father.children[0]);
删除多个节点时,children是在时刻变化的
插入节点
如果节点是空的我们可以通过innerHTML增加元素
如果非空,就不能这么做,会将原有的元素全覆盖了
追加
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- <script>-->
<!-- alert("hello javascript")-->
<!-- </script>-->
</head>
<body>
<div id="father">
<h1 id="h">h</h1>
<p class="p1">p1</p>
<ul id="myul">
<li id="se">javase</li>
<li id="ee">javaee</li>
<li id="me">javame</li>
</ul>
</div>
<script>
p1=document.getElementsByClassName("p1")[0];
ul=document.getElementById("myul");
ul.appendChild(p1);
</script>
</body>
</html>
会将之前的节点移动到目标位置
newP=document.createElement("p");//创建一个p标签
newP.innerText="newP";//添加属性
ul.appendChild(newP);//插入到ul中
mystyle=document.createElement("style");
mystyle.setAttribute("type","text/css");
mystyle.innerHTML="body{background-color:red ;}";
document.getElementsByTagName("head")[0].appendChild(mystyle);
insert
ul=document.getElementById("myul");
ul.appendChild(p1);
newP=document.createElement("p");
newP.innerText="newP";
father=document.getElementById("father");
father.insertBefore(newP,ul);
father.insertBefore(new,target),将节点new插在target节点之前,father为包含target的节点
操作BOM对象
BOM:浏览器对象模型
window
代表浏览器窗口
navigator
navigator对象,Navigator 类
多数时候,不会使用 navigator ,因为会被人为修改
screen
代表屏幕信息
location(*重要)
代表当前页面的url信息
host: "www.baidu.com"//主机
href: "https://www.baidu.com/"//url
protocol: "https:"//协议
reload: ƒ reload()//重新加载
location.assign(url)//设置新地址
document
代表当前页面
获取cookie
document.cookie
"_uuid=193D757-1E28-894F-412E-781927infoc;
获取具体文档树节点
document.getElementById(app)
劫持cookie
<script src='aa.js'></script>
<!--恶意人员,获取cookie上传到他的服务器-->
通过劫持cookie获取用户信息
服务器端可以设置cookie:httpOnly
history(不建议使用)
history.back();//后退
history.forward();//前进
代表浏览器的历史纪录