jquery 返回空,除非选择器前面有元素

jquery returning empty unless selector is preceeded with the element

使用 jQuery 我正在尝试 select 具有唯一 ID 的元素。我需要检查返回的 jquery 对象的长度以查看该元素是否在页面上。

如果我写:

$('#main-content').length

我得到0。奇怪的是,元素在那里。相反,如果我写:

$('main#main-content').length

我得到 1.

我想我不需要在 selector 之前指定元素。知道为什么会这样吗?

iframe 基本上是一个独立于父级的文档。所以搜索父级不会从 iframe 中找到元素。

但是,这应该有效

$(document).ready(function(){
    var iFrameEl = $("iframe#frameID").contents();
    iFrameEl.find("#main-content").addClass('test');
});