abstract: //根据name标签名和name属性选择元素的快捷方式:仅适用于极少的几个,这是历史原因造成的 // images: 所有的<img>元素 图像,数组, 有三种访问方式 document.images[0].style.width = '200px';
//根据name标签名和name属性选择元素的快捷方式:仅适用于极少的几个,这是历史原因造成的
// images: 所有的<img>元素 图像,数组, 有三种访问方式
document.images[0].style.width = '200px'; // 1.标签索引
document.images['pic'].style.width = '200px'; // 2.name 属性
document.images.pic.style.width = '300px'; // 3.将name视为元素对象的属性进行访问
// forms: 所有的<forms>元素 表单,数组
document.forms[0].style.backgroundColor = 'lightgreen';
document.forms['register'].style.backgroundColor = 'lightblue';
document.forms.register.style.backgroundColor = 'red';
document.forms.item(0).style.backgroundColor = 'lightgreen'; // 类数组可用item()方法获取某个元素
//a 链接: 所有的<a>元素,NodeList 数组
document.links[0].style.backgroundColor = 'yellow';
document.links['php'].style.backgroundColor = 'red';
document.links.php.style.backgroundColor = 'green';
// body: <body>元素,总有定义,只有一个
document.body.style.backgroundColor = 'wheat';
// head: <head>元素,总有定义,不写会自动添加,只有一个
let style = document.createElement('style');
document.head.appendChild(style);
// .red 获取 class="red"的元素,其实js也支持使用css选择器获取元素
let lists = document.querySelectorAll('li');
console.log(lists); //返回节点列表数组,里面每个元素对应一个元素
//可以使用
lists[0].style.backgroundColor = 'coral';
lists.item(1).style.backgroundColor = 'lightblue';
//该方法还可以在元素上调用,这也根据标签和class类名获取元素是一样的
let ul = document.querySelector('#ul'); // 获取满足条件的第一个元素
console.log(ul); // 只返回ul列表元素以及内部子元素
let li = ul.querySelectorAll('.green');
for (let i = 0; i < li.length; i++) {
li[i].style.backgroundColor = 'green';
}
Correcting teacher:天蓬老师Correction time:2018-12-30 13:41:12
Teacher's summary:其实, jQuery中的选择器, 底层代码 , 就是用这几个方法来实现的, 是不是很方便呢?