getElementsByTagName()
方法返HTMLCollection
對象。
HTMLCollection 對象相似包含 HTML 元素的一個數組。
注意:html
大部分瀏覽器的querySelectorAll()
返回 NodeList 對象。
注意數組
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <P>1</P> <P id="p2">2</P> <P>3</P> <P>4</P> <P>5</P> <script> // getElementsByTagName() 方法返回 HTMLCollection 對象。 const myCollection = document.getElementsByTagName('p'); console.log(myCollection) // 大部分瀏覽器的 querySelectorAll() 返回 NodeList 對象。 const myNodeList = document.querySelectorAll("p"); console.log(myNodeList) console.log(myNodeList ===myCollection) //false console.log(myCollection.p2) // <P id="p2">2</P> console.log(myNodeList.p2) //undefine </script> </body> </html>