一、Dom操作
1.查找元素
document.getElementById(id值) 元素本身
document.getElementsTagName(标签名) 集合
document.getElementsTagName(标签名)[0]
document.getElementsByName(name属性值) 集合
<div name="d1">a1...</div>
document.body
document.all
document.images 页面中所有<img>
document.links 页面中所有a
DOM扩展:
querySelector()
接收css选择符,返回与该模式匹配的“第一个”元素,
如没找到返回null
document.querySelector("#id01")
document.querySelector(".c1")
document.querySelector("div") querySelectorAll()
返回所有匹配的元素 以集合的形式返回
2.元素创建
createElement 创建元素节点
createTextNode 创建文本节点
3.元素新增
appendChild 元素的追加
父节点.appendChild(子节点)
insertBefore 元素的插入
父节点.insertBefore(新的子节点,旧的子节点(准备插入的位置))
4.元素的删除
removeChild 元素的删除
5.内容管理
innerText 文本内容
innerHtml 文本+样式
6.属性管理
setAttribute()
getAttribute()
removeAttribute
二、样式
1.classList (html新增)
// console.log(document.querySelector("div").classList.length);//3
// console.log(document.querySelector("div").classList.item(1));//b1
// console.log(document.querySelector("div").classList.remove("c1"));
// console.log(document.querySelector("div").classList.add("c1"));
// console.log(document.querySelector("div").classList.toggle("a1"));//切换
console.log(document.querySelector("div").classList.contains("b1"));//true
classList.length class样式个数
classList.item(1) 第几个样式名称
classList.remove("c1") 删除样式
classList.add("c1") 新增样式
class.toggle("a1") 切换样式,a1存在则删除,不存在则添加
classaList.contains("b1") 判断是否有指定样式
2.style访问元素
// v1.style.color="red"
// v1.style.width="100px"
// v1.style.backgroundColor="yellow"
// v1.style.float="right" //高版本浏览器
// v1.style.cssFloat="right" //低版本浏览器
alert(v1.style.color)
3、cssText
v1.style.cssText="color:red;width:200px;background-color:yellow"
语法要与css一致
将行内样式变成js代码实现
4.样式属性
v1.style.removeProperty("background-color")
v1.style.setProperty("height","300px")
console.log(v1.style.getPropertyValue("color"));
5.外部css属性
// var v1=document.querySelector("#id01")
// var css1=getComputedStyle(v1,null)
// console.log(css1.width); //只能查询,不能修改
// v1.style.width="500px" //此方法可修改