摘要:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>通過(guò)css選擇器獲取元素</title> </head> <body> <ul id="ul"> &l
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>通過(guò)css選擇器獲取元素</title> </head> <body> <ul id="ul"> <li>列表項(xiàng)1</li> <li class="">列表項(xiàng)2</li> <li>列表項(xiàng)3</li> <li>列表項(xiàng)4</li> <li class=" coral large">列表項(xiàng)5</li> </ul> <script type="text/javascript"> let lists =document.querySelectorAll('li');//返回滿(mǎn)足條件的所有 console.log(lists); lists[0].style.backgroundColor = 'coral'; lists.item(1).style.backgroundColor ='lightgreen'; let ul = document.querySelector('#ul');//返回滿(mǎn)足條件的第一個(gè) console.log(ul); let li =ul.querySelectorAll('.green'); console.log(li); for(let i =0;i<li.length;i++){ li[i].style.backgroundColor = 'green'; } </script> </body> </html>
document.querySelectorAll()返回所有,document.querySelector()返回第一一個(gè)
批改老師:天蓬老師批改時(shí)間:2018-11-28 17:39:47
老師總結(jié):querySelector() 以及 querySelectorAll(), 這是jQuery獲取元素的最主要的方式, 現(xiàn)代的js引擎,都會(huì)實(shí)現(xiàn)這二個(gè)功能