摘要:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <img src="images/1.png"
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <img src="images/1.png" name="img1" alt=""> <ul> <li id="li1">列表項(xiàng)01</li> <li>列表項(xiàng)02</li> <li>列表項(xiàng)03</li> <li>列表項(xiàng)04</li> <li>列表項(xiàng)05</li> </ul> <a href="" name="a1">111</a> </body> <script> let li = document.getElementById('li1');//id選擇器 console.log(li); li.style.background = "lightblue"; let li3 = document.getElementsByClassName('li3')[0];//class選擇器 li3.style.background = 'lightyellow'; document.getElementsByClassName('li3').item(0).style.background = 'lightgreen'; let a1 = document.links[0]; console.log(a1); a1.style.background = 'lightblue'; a1.href = 'http://www.baidu.com/'; let img1 = document.getElementsByName('img1')[0];//name選擇器 console.log(img1); img1.style.width="200px"; let ul = document.getElementsByTagName('ul').item(0);//元素選擇器 ul.lastElementChild.style.background = 'lightyellow'; li = document.querySelector(".li3");//css選擇器 及時(shí)有多個(gè)也返回所有元素的第一個(gè)元素 console.log(li) li = document.querySelectorAll("li").item(1);//css選擇器返回?cái)?shù)組 console.log(li); /* let c = 1; const a = 4; function test(){ let c = 2; console.log(c); } test(); console.log(c); console.log(a); */ </script> </html>
DOM選擇器中4個(gè)常用選擇器,和2個(gè)css選擇器
document.getElementById(); //DOM中的ID選擇器 返回一個(gè)元素對象
document.getElementsByName(); //DOM中的name選擇器 返回一個(gè)對象/數(shù)組集合
document.getElementsByTagName(); //DOM中的元素名稱選擇器 返回一個(gè)對象/數(shù)組集合
document.getElementsByClassName(); //DOM中的類名選擇器 返回一個(gè)對象/數(shù)組集合
document.querySelector(); //DOM中CSS選擇器,返回的一個(gè)元素,如果匹配多個(gè)則返回?cái)?shù)組中第一個(gè)元素
document.querySelectorAll(); //DOM中CSS選擇器 返回一個(gè)對象/數(shù)組集合
批改老師:韋小寶批改時(shí)間:2019-02-28 13:08:33
老師總結(jié):選擇器是很重要的 選擇器掌握不了 其他的都別想了 課后一定要多去練習(xí)