1. 通過 id 查詢 HTML 元素
<!DOCTYPE html> <html> <body> <p id = "intro">Hello World!</p> <p>本示例演示<b>getElementById</b>方法!</p> <script> x = document.getElementById("intro"); document.write(`<p>id="intro"的段落中的文字是:` + x.innerHTML + `</p>`); </script> </body> </html>
2. 通過標籤名查詢 HTML 元素
<!DOCTYPE html> <html> <body> <p>Hello World!</p> <div id = "main"> <p>The DOM is very useful.</p> <p>本示例演示 <b>getElementsByTagName</b>方法。</p> </div> <script> try { var x=document.getElementById("main"); var y=x.getElementsByTagName("p"); document.write(`id為“main”的div中的第一段文字是:` + y[0].innerHTML); } catch(err) { document.write("程式碼出錯了,老弟"); } </script> </body> </html>