<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>test</title> </head> <body> <p id="p1">1</p> <p class="p">2</p> <p class="p">3</p> <script> window.onload = function(){ document.getElementsByName document.getElementsByTagName console.log(document.getElementById('p1'));//<p id="p1">1</p> console.log(document.getElementById('p2'));//null,找不到 console.log(document.getElementsByClassName('p'))//HTMLCollection(2) [p.p, p.p],返回類數組的對象集合 console.log(document.querySelector('#p1'));//<p id="p1">1</p> console.log(document.querySelector('#p2'));//null,找不到返回null console.log(document.querySelector('p'));//<p id="p1">1</p>,返回匹配到的第一個節點 console.log(document.querySelectorAll('p'));//NodeList(3) [p#p1, p.p2, p],返回匹配到的類數組的對象集合 console.log(document.querySelectorAll('p').pop());//test.html:24 Uncaught TypeError: document.querySelectorAll(...).pop is not a function } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>test</title> <style> .red{ color:red; } </style> </head> <body> <p id="p" class="p-default">1</p> <p>2</p> <script> window.onload = function(){ // document.getElementById('p').style.color = 'red'; // document.getElementById('p').className = 'red';//直接給選定節點設置類名,會覆蓋掉原有的類 // document.getElementById('p').classList.add('red');//直接給節點添加一個類,排在原有類的後面,添加已有的類名。及不操做 // document.getElementById('p').classList.remove('p-default');//刪去選定的類 // document.getElementById('p').setAttribute('class','red');//直接向html標籤裏添加class="xxx"的屬性 } </script> </body> </html>
以上要注意是何時是 HTMLCollection,何時是NodeList,二者的具體區別,待後續補充吧。css