document.querySelector和document.body.querySelector有什么区别? [重复]

问题描述 投票:0回答:2
当我在控制台上记录document.body.querySelector('input')和document.querySelector('input')时,我得到了相同的对象。这怎么可能?如果它们相同(实际上它们相同,则将它们与===运算符进行比较,并返回true)那么“身体”扮演什么角色呢?

document.body.querySelector和document.querySelector有什么区别?

javascript html object dom
2个回答
1
投票
使用document.body.querySelector,您可以将元素包含在'body'标签中,而document.querySelector将从整个文档中返回元素

0
投票
<!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <h2 class="example">A heading with class="example"</h2> <p class="example">A paragraph with class="example".</p> <p>Click the button to add a background color to the first element in the document with class="example".</p> <button onclick="myFunction()">Submit</button> <script> function myFunction() { //document.body.querySelector('title').text = "title changed"; //Uncaught TypeError: Cannot set property 'text' of null document.querySelector('title').text = "title changed"; // work fine // document.body trageting only those elements which are inside body tag. } </script> </body> </html>
© www.soinside.com 2019 - 2024. All rights reserved.