代码:获取某个标签对象
<!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> <h1 class="title1">hello</h1> <h2 class="title2">HELLO</h2> <script> // 选中h1 let title1 = document.querySelector(".title1") // 选中h2 let title2 = document.querySelector(".title2") // 控制台输出节点 console.log(title1) console.log(title2) </script> </body> </html>
效果图:
代码:获取多个标签对象
<!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> <h1 class="title">hello</h1> <h2 class="title">HELLO</h2> <script> // 选中多个元素,包含在一个伪数组里面 let titles = document.querySelectorAll(".title") // 控制台解套输出 console.log(titles) // titles 是伪数组 console.log(titles[0]) console.log(titles[1]) </script> </body> </html>
效果图:
web API-DOM-js选中元素
最新推荐文章于 2024-10-12 10:19:22 发布
该文演示了如何使用JavaScript的querySelector和querySelectorAll方法来选取HTML文档中的特定标签。querySelector用于获取匹配CSS选择器的第一个元素,而querySelectorAll返回所有匹配元素的NodeList(伪数组)。
摘要由CSDN通过智能技术生成