开发者

When document.getElementById() doesn't?

I have some JavaScript that obtains elements by ID from an HTML document.

In one particular scenario, the docum开发者_JS百科ent.getElementById(idString) method returns null in IE8 compatibility mode, however the jQuery equivalent works. 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.

Any avenues to investigate appreciated.


Update - actually, myjQueryDiv is also empty, but I guess jQuery makes it not null. However, the call parentDom.find("#" + myId); does return the correct element, where parentDom is an ancestor of the element I need to find.


According to MSDN...

In IE8 Standards mode, getElementById performs a case-sensitive match on the ID attribute only. 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.

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. You can check the .length or value at [0] to see if it actually matched any elements.


Works fine for me

  • your code
  • added innerHTML & html()


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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜