简体   繁体   English

当document.getElementById()没有?

[英]When document.getElementById() doesn't?

I have some JavaScript that obtains elements by ID from an HTML document. 我有一些JavaScript从HTML文档中通过ID获取元素。

In one particular scenario, the document.getElementById(idString) method returns null in IE8 compatibility mode, however the jQuery equivalent works. 在一个特定场景中,document.getElementById(idString)方法在IE8兼容模式下返回null,但是jQuery等效方法有效。 I need to work out why the native call isn't working. 我需要弄清楚为什么原生呼叫不起作用。

Here's an example: 这是一个例子:

var myId = "e_" + someId;
var myNativeDiv = document.getElementById(myId);
var myjQueryDiv = $("#" + myId);
alert(myNativeDiv + " - " + myjQueryDiv); // alerts "null - [Object object]"

I've checked that myId is unique in the document. 我已经检查过myId在文档中是唯一的。

Any avenues to investigate appreciated. 任何调查途径都值得赞赏。


Update - actually, myjQueryDiv is also empty, but I guess jQuery makes it not null. 更新 - 实际上, myjQueryDiv也是空的,但我猜jQuery使它不为空。 However, the call parentDom.find("#" + myId); 但是,调用parentDom.find("#" + myId); does return the correct element, where parentDom is an ancestor of the element I need to find. 返回正确的元素,其中parentDom是我需要找到的元素的祖先。

According to MSDN ... 根据MSDN ...

In IE8 Standards mode, getElementById performs a case-sensitive match on the ID attribute only. 在IE8标准模式下, getElementById仅对ID属性执行区分大小写的匹配。 In IE7 Standards mode and previous modes, this method performs a case-insensitive match on both the ID and NAME attributes, which might produce unexpected results. 在IE7标准模式和以前的模式中,此方法对ID和NAME属性执行不区分大小写的匹配,这可能会产生意外结果。

It's possible that your code relies on one of these behaviours. 您的代码可能依赖于这些行为之一。


jQuery wraps its results in a jQuery object , so that things like $(".unused-class").remove() don't raise errors. jQuery将其结果包装在jQuery对象中 ,因此像$(".unused-class").remove()这样的东西不会引发错误。 You can check the .length or value at [0] to see if it actually matched any elements. 您可以检查[0]处的.length或值,看看它是否与任何元素匹配。

OK so here's the answer. 好的,这就是答案。

I had previously detach() ed an ancestor element, so jQuery find could see the element by ID when executed from an ancestor element in the detached fragment. 我之前已经detach()了一个祖先元素,所以当从分离片段中的祖先元素执行时,jQuery find可以通过ID看到该元素。

Of course both jQuery find with no context and the native method correctly did not return the element, as it was not at that point part of the document . 当然,两个jQuery都没有上下文,而且本机方法没有返回元素,因为它不是document那一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM