我需要使用 jQuery 选择器,但它返回 null。普通的、旧的 DOM 函数可以工作。我正在尝试操纵这个:
<ul id="lhs_container">LI elements and HTML</ul>
这是我的测试代码:
$(document).ready(function() {
if(document.getElementById("lhs_container")){
console.log("DOM was there"); //this is logged in the console
console.log($("#lhs_container").html()); //this blows up (error below)
}
});
我收到的错误是:
Uncaught TypeError: Cannot read property 'html' of null
at HTMLDocument
我也尝试过其他 jQuery 操纵器(追加等),它们都会导致错误。有谁知道这可能是什么原因造成的?我要拔头发了!
最佳答案
$(document).ready(function() {
if(document.getElementById("lhs_container")){
console.log("DOM was there");
console.log($("#lhs_container").html());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="lhs_container">LI elements and HTML</ul>
</body>
</html>
我得到了正确的输出。检查是否正确添加了jquery库。
关于javascript - jQuery 选择器返回 null,而 DOM 函数工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46914007/