javascript - jQuery 选择器返回 null,而 DOM 函数工作正常

标签 javascript jquery dom jquery-selectors

我需要使用 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/

相关文章:

javascript - 未捕获的类型错误 : Cannot read property 'name' of undefined

HTML 双击选择异常

javascript - 导出 DOM 的当前样式

javascript - 从下拉列表中选择 javascript 事件

javascript - 悬停时在链接中显示 Bootstrap 字形

javascript - 用javascript计算两点之间的方位

javascript - Angular 工厂 : update scope with progress during upload

javascript - 检查时空对象返回 false

jquery - 禁止点击 div 元素

javascript - @media 查询被 javascript DOM 操作覆盖