javascript/jQuery can't find element with messed up id
I'm trying to access an element in MS CRM 2011 with the following id: account|NoRelationship|Form|B_GenerateInvoice-Large
I can see this element in the IE developer tools:
Unfortunately I always get null when trying to find this element.
I've tried the following:
alert(document.getElementById('account|NoRelationship|Form|B_GenerateInvoice-Large'));
alert($("[id='account|NoRelationship|Form|B_GenerateInvoice-Large]").html());
alert($(jq("account|NoRelationship|Form|B_GenerateInvoice-Large")).html()); // jq() adds the '#' and escapes special characters
alert($("#account|NoRelationship|Form|B_GenerateInvoice-Large").html());
alert(document.getElementById("#account\\|NoRelationship\\|Form\\|B_GenerateInvoice-Large"));
alert($("#account\\|NoRelationship\\|Form\\|B_GenerateInvoice-Large").html());
These all fail to find the element.
Am I missing something obvious here?
Solution:
The javascript was inside an iframe while the element was outside of the iframe..
I did not manage to solve it.
The jQuery Manual on Selectors states:
If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors.
So try this one:
$('#account\\|NoRelationship\\|Form\\|B_GenerateInvoice-Large')...
jsFiddle Demo
EDIT: I have successfully tested my Fiddle in Chrome, Firefox 4, IE9, IE8 and IE7, it works fine.
It may be a bug in browser, since HTML5 specification allows any character except spaces in id attribute
ID #
Any string, with the following restrictions:
must be at least one character long
must not contain any space characters
however, it is encrouaged not to put any weired character in id attribute, only number, letter and underscore there:)
From the jQuery documentation:
If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\.bar").
So this should work:
alert($("#account\\|NoRelationship\\|Form\\|B_GenerateInvoice-Large").html());
And it does, indeed: http://jsfiddle.net/Cdz9w/
What version of HTML is the page declaring that it's using? Because that's a valid HTML5 id
, but it's an invalid HTML4.01 and earlier id
. (It's also an invalid CSS id
, which is vaguely relevant if you use something like jQuery to look it up, as jQuery uses CSS selectors.)
The fiddle in @bazmegakapa's answer works for me on Chrome, but perhaps your page is declaring a different version of HTML, or perhaps a less-advanced browser doesn't like it, etc.
精彩评论