查找
- 根据id获取元素 getElementById() 返回符合条件的第一个对象
var aa = document.getElementById("aa")
console.log(aa)
- 根据class获取元素
var aa = document.getElementsByClassName("demo")
console.log(aa)
// aa[0].onclick = function() {
// aa[0].style.background = "red"
// }
// aa[1].onclick = function() {
// aa[1].style.background = "red"
// }
// aa[2].onclick = function() {
// aa[2].style.background = "red"
// }
// aa[3].onclick = function() {
// aa[3].style.background = "red"
// }
for (var i = 0; i < aa.length; i++) {
console.log(i)
aa[i].onclick = function() {
console.log(this)//当前点击对象加样式
this.style.background = "blue"
}
}
- 根据元素名称(标签名称)获取元素getElementsByTagName() 返回所有符合条件的对象组成的数组
var aa = document.getElementsByTagName("div")
console.log(aa[2])
- 根据选择器获取元素querySelector() 返回符合条件的第一个对象
var aa = document.querySelector("div")
console.log(aa)
- 根据选择器获取元素 querySelectorAll() 返回所有符合条件的对象组成的数组
var aa = document.querySelectorAll("div")
console.log(aa[0])
//通过关系查找
//parentNode parentElement 父级元素
//childNodes children 子级元素
//firstChild == childNodes[0] 第一个元素
//lastchild == lastElementChild 最后一个元素
//nextSibling nextElementSibling下一个兄弟
//previousSibling previousElementSibling 上一个兄弟
var aa = document.getElementById("aaa")
console.log(aa)
// console.log(aa.parentNode)
// console.log(aa.childNodes)
console.log(aa.nextElementSibling)
console.log(aa.previousElementSibling)
修改
- 修改内容
//innerHTML 把修改内容当作标签处理
//innerText 把修改内容当作文本处理
//value 修改收集用户信息的标签
var aa = document.getElementById("aaa")
console.log(aa)
console.dir(aa)
aa.innerText = "<a href=''>跳转</a>"
aa.value = "hello"
- 修改样式
//obj.style.属性 = 值
var aa = document.getElementById("aaa")
console.log(aa)
console.dir(aa)
aa.style.background = "red"
aa.style.color = "yellow"
aa.style.f0ontSize = "5px"
aa.style.cssText = "background:red;color:yellow;front-size:50px"
aa.className = "test"
- 修改属性
//原生属性
aa.id = "aaaaaa"
aa.className = "ttt"
aa.href = "https://baidu.com"
//自定义属性
//getAttribute()获取 setAttribute()设置
console.log(aa.getAttribute("index"))
aa.setAttribute("index", "789")
添加
- 创建元素
//1、①创建元素
var div = document.createElement("div")
div.className = "demo"
div.innerHTML = "hello"
div.onclick = function() {
alert(111)
}
console.log(div)
//②复制 cloneNode() 参数为true 连内容一起复制; false:浅复制,只复制外壳
var old = document.querySelector("h4")
var nameNode = old.cloneNode(true)
console.log(nameNode)
- 添加元素
//在元素的最后子元素位置添加:appendChild()
//在元素的某个位置插入 insertBefore(要插入的元素,在那个节点前插入) insertBrefor(div,null)
- 替换节点:replaceChild(新元素,要被替换掉的元素)
var aa = document.getElementById("aa")
console.log(aa)
var p = document.querySelector("p")
console.log(p)
aa.replaceChild(newNode, p)
删除
//除 找到父级,父级调用删除方法 removeChild()
var aa = document.getElementById("aa")
var p = document.querySelector("p")
p.parentNode.removeChild(p)