dom操作
获取dom
标签名获取
doucment.getElementsByTagName("div")
document.querySelector("div")
className获取
document.getElementsByClassName("class") // 伪数组,注意后面不需要家点了,其实前面已经很明确了
document.querySelectorAll(".class") // 伪数组
document.querySelector(".class") // 第一个符合要求的dom元素
前两个获取的是所有含有"class"这个类名的dom,返回一个类数组
最后一个是获取第一个含有"class"类名的dom
id获取
document.getElementById("myId")
document.querySelector("#myId")
操作类名
类名的增删改查
dom.classList // 获取类名,返回数组
dom.classList.add("newName") // 添加类名
dom.classList.remove("newName") // 删除类名
返回类名的数组 dom.classList[0]可获取第一个类名
用它来添加类名不会覆盖原来的
dom.className
dom.className="newName"
获取或设置className属性,获取的话,返回的是以空格分割的字符串,没有classList方便
如果直接用className=“newName”,会覆盖它原有的类名,只剩下新类名
操作style
dom.style.属性名="属性值" // 添加或修改样式,不会影响原有的其他样式
dom.style.removeProperty("属性名") // 删除style中某个属性,不会影响其他样式的生效
操作属性
dom.setAttribute("属性名","属性值")
dom.getAttribute("属性名")
dom.hasAttribute("属性名")
dom.removeAttribute("属性名")
操作内容
dom.innerHTML // 获取内容
dom.innerHTML="新的内容" // 修改内容
创建添加、删除dom
const child=document.createElement("span") // 创建dom
const box=document.querySlector(".box")
box.appendChild(child) // 添加dom; 放在最后,当box的最后一个亲儿子
document.querySelector('span').remove // 删除dom