使用ID获取元素
id选择器getElementById
用于精确查找,如是没有找到则返回null
对于id选择器,若页面中存在多个id相同,则css样式对所有的该id名的元素都生效,但是js脚本只对第一个名为id的元素生效。
获取和设置元素内容
innerText方法
返回标签内的文本值,不包含代码
innerHTML方法
返回是html标签中的内容,可能包含代码
这是内容
var a = document.getElementById("zxw");
var b = a.innerText;
var c = a.innerHTML;
console.log(b)
console.log(c)
获取和设置元素属性
先获取,然后可以直接设置
var a = document.getElementById("zxw");
console.log(a.value)
console.log(a.type)
a.value = "Button"; //修改
a.title = "添加后的title"; //设置
console.log(a.title)
获取和设置元素属性的通用方法
getAttribute(“属性名”)
setAttribute(“属性名”,“属性值”)
var a = document.getElementById("zxw");
var b = a.getAttribute("value"); //获取a元素value值
a.setAttribute("id","zwxxgd") //设置a元素的id值为zwxxgd
console.log(b)
console.log(a.id)
获取或设置行内样式
获取行内样式:document.getElementById(“zxw”).style.cssText根据id获取元素后设置行内样式:a.style.cssText =“color:red”
这是一个div元素
var a = document.getElementById("zxw")
a.style.cssText ="color:red"; //设置a的行内样式
console.log(a.style.cssText)
var b = document.getElementById("zxw").style.cssText; //获取行内样式
b = "font-size:12px" //b本身就为行内样式了,因此可以直接改
console.log(b)
获取行内样式中的属性
获取行内样式中的某个样式:
元素.style.某个样式console.log(a.style.color)
设置:
注意:若要属性名中有-,要使用驼峰命名法a.style.backgroundColor = “blue”
添加和删除类名
已有相同的类名时不添加
var a = document.getElementById("zxw")
a.classList.add("zxw1","zxw2","zxw3") //添加类名
删除的类名不存在时也不会报错
a.classList.remove("zxw2") //删除类名
切换类名:若有相同的类名时执行删除,没有时执行添加
a.classList.toggle("abcd") //切换类名
强制删除or添加类名
a.classList.toggle("zxw1",true) //强制添加(true),删除(false)
使用类名获取元素
(类选择器)
getElementsByClassName(“zxw”)返回所有的指定元素,而不是一个元素可以当成数组处理
var a = document.getElementsByClassName("zxw")
a[0].style.color = "red" //选取的数组内容必须写,代表给第几个元素的设置
// 给获取到的全部元素都设置
for(var i=0;i a[i].style.backgroundColor = "gray" } console.log(a) 使用标签以及name属性获取元素 标签名选择器 getElementsByTagName(“p”) 选取所有指定标签名的一组元素,而不是一个元素 使用组合方式获取元素 只有两种写法是对的 var a = document.getElementById("zxw").getElementsByTagName("p"); console.log(a); var b = document.getElementById("zxw").getElementsByClassName("zxw2"); console.log(b) 使用CSS选择器获取元素 返回文档中匹配指定CSS选择器的所有元素语法:querySelectorAll(“css选择器”)返回文档中匹配指定CSS选择的第一个元素语法:querySelector(“css选择器”) 这是一个div元素 第二个div元素
var a = document.querySelectorAll("#zxw,.zxw2");
console.log(a);
var b = document.querySelector("#zxw p")
console.log(b)