サマリー: //根據(jù)name標(biāo)簽名和name屬性選擇元素的快捷方式:僅適用于極少的幾個,這是歷史原因造成的 // images: 所有的<img>元素 圖像,數(shù)組, 有三種訪問方式 document.images[0].style.width = '200px';
//根據(jù)name標(biāo)簽名和name屬性選擇元素的快捷方式:僅適用于極少的幾個,這是歷史原因造成的
// images: 所有的<img>元素 圖像,數(shù)組, 有三種訪問方式
document.images[0].style.width = '200px'; // 1.標(biāo)簽索引
document.images['pic'].style.width = '200px'; // 2.name 屬性
document.images.pic.style.width = '300px'; // 3.將name視為元素對象的屬性進(jìn)行訪問
// forms: 所有的<forms>元素 表單,數(shù)組
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'; // 類數(shù)組可用item()方法獲取某個元素
//a 鏈接: 所有的<a>元素,NodeList 數(shù)組
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); //返回節(jié)點列表數(shù)組,里面每個元素對應(yīng)一個元素
//可以使用
lists[0].style.backgroundColor = 'coral';
lists.item(1).style.backgroundColor = 'lightblue';
//該方法還可以在元素上調(diào)用,這也根據(jù)標(biāo)簽和class類名獲取元素是一樣的
let ul = document.querySelector('#ul'); // 獲取滿足條件的第一個元素
console.log(ul); // 只返回ul列表元素以及內(nèi)部子元素
let li = ul.querySelectorAll('.green');
for (let i = 0; i < li.length; i++) {
li[i].style.backgroundColor = 'green';
}
添削の先生:天蓬老師添削時間:2018-12-30 13:41:12
先生のまとめ:其實, jQuery中的選擇器, 底層代碼 , 就是用這幾個方法來實現(xiàn)的, 是不是很方便呢?