I have some JavaScript that obtains elements by ID from an HTML document.
In one particular scenario, the document.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.
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.