<!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