- JS基础知识,规定语法(ECMA 262 规范)
- JS Web API,网页操作的API(W3C规范)
JS Web API:
- DOM
- BOM
- 事件绑定
- ajax
- 存储
DOM(document object model)的实质
获取DOM节点
//html和css//css.container{ border:1px solid #ccc; height:50px;}.red{ color:red;}//html<div id="div1"> <p>这是一段文字1</p> <p>这是一段文字2</p> <p>这是一段文字3</p><div><div class="container"> 内容</div>
const div1 = document.getElementById('div1');//元素const divList = doucument.getElementsByTagName('div')//汇合console.log(divList.length,divList[0])const containerList = doucument.getElelmentsByClassName("container") //汇合const pList = document.querySelectorAll("p") //汇合
property和attribute
- property:批改对象属性,不会体现在html构造中。
- attribute:批改html属性,会扭转html构造。
- 两者都可能引起DOM从新渲染。(尽量用property)
js
const pList = doucument.querySelectorAll('p')const p1 = pList[0]
property模式(对dom元素js变量进行批改)
p1.style.width="100px"console.log(p1.style.width)p1.calssName = "red"console.log(p1.calssName)console.log(p1.nodeName)//打印的是节点名称pconsole.log(p1.nodeType)//打印节点类型1
attribute模式(设置的是节点属性)
p1.setAttribute("class","container")console.log(p1.getAttribute("class"))
DOM构造操作
- 新增/插入节点
- 获取子元素列表,获取父元素
- 删除字节点
const div1 = document.getElementById("div1")//增加新节点const newP = document.createElement('p')newP.innerHTML = "this is p1"div1.appendChild(newP)//增加新创建的元素//挪动已有节点,留神是挪动const p2 = document.getElementById('p2')div1.appendChild(p2)//获取子元素列表const div1 = doucument.getElementById("div1")const div1ChildNodes = div1.childNodesconsole.log(div1.childNodes)//打印出两种标签,一种是p标签,一种是text标签,因为p标签外面含有文本,text的nodeType为3,p的nodeType为1,所以通过转化为数组过滤。const div1ChildNodesP = Array.prototype.slice.call(div1.childNodes).filter(child=>{ if(child.nodeType == 1){ return true } return false})//删除子节点div1.removeChild(div1ChildNodesP[0])//获取父元素const div1 = document.getElementById("div1")const parent = div1.parentNode