HTML document.querySelector返回null但元素存在
document.querySelector() 将返回与指定的选择器组匹配的第一个元素。如果没有找到匹配项,则返回“null”。
语法:
let input = document.querySelector("input.email");
它将返回具有’class’属性为’email’的第一个输入元素。
现在让我们讨论错误“document.querySelector返回null,但元素存在”
示例1 : 让我们看一下“id”选择器的错误。在这个选择器中,querySelector的值中缺少#(哈希)。#表示我们正在选择“id”选择器。在输出中,当我们点击提交按钮时,我们可以看到以下错误。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<h2 style="color:green;">GeeksforGeeks</h2>
<button id="out">Submit</button>
<script>
const get = document.querySelector('out')
get.addEventListener('click',(e)=>{
get.style.backgroundColor='red';
get.innerHTML="Hii GFG , How r u???"
})
</script>
</body>
</html>
输出:
示例2: 接下来让我们看一下类选择器的错误。在这个 . 中,querySelector() 的值中缺少了点。 . 点表示我们选择了类选择器。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<h2 style="color:green">GeeksforGeeks</h2>
<button class="out">Submit</button>
<script>
const get = document.querySelector('out')
get.addEventListener('click',(e)=>{
get.style.backgroundColor='red';
get.innerHTML="Hii GFG , How r u???"
})
</script>
</body>
</html>
输出:
- 点击提交按钮时:
- 当在“Source”部分点击文件时:
注意: 两者都会产生相同的错误,因为开发者需要指定选择器的类型(id或class)。在这两个示例中,都缺少了这个部分,所以输出的图片中会显示相同的错误信息。
示例 3: 以下代码展示了解决上述问题的方法。我们需要明确指定我们使用的选择器的类型,如下所示。由于代码能够正常工作,所以我们得到了正确的输出。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<h2 style="color:green">GeeksforGeeks</h2>
<button class="out">Submit</button>
<script>
const get = document.querySelector('.out')
get.addEventListener('click',(e)=>{
get.style.backgroundColor='red';
get.innerHTML="Hii GFG , How r u???"
})
</script>
</body>
</html>
输出: