Reputation: 47512
I have following id for one of my div id="ftbutton_1357567084/Team:8/User:10/Image:195"
i want to replace its html after ajax being called.
When i try to do this using jQuery something like following it doesn't work
jQuery("#"+id).html(SOME HTML HERE);
Where as following code works
document.getElementById(id).innerHTML = SOME HTML HERE;
I know ID should not contain some special characters
ID attributes should be = after an initial letter (a-z or A-Z), may also use
periods and colons, in addition to letters, numbers, hyphens, and underscores.
Ref How do I select an element by an ID that has characters used in CSS notation?
But for some reason i can't change the id of each element as it is thought the site.
I also tried following but it doesn't works
function jq( myid ) {
return "#" + myid.replace( /(:|\.)/g, "\\$1" );
}
jQuery(jq("#"+id)).html(SOME HTML HERE);
I just want to know if this is a case, do i need to use document.getElementById(""+id)
instead jQuery("#"+id)
?
OR in other words
Is document.getElementById(""+id)
is more reliable than jQuery("#"+id)
?
Upvotes: 3
Views: 630
Reputation: 32076
Do this:
$('[id="ftbutton_1357567084/Team:8/User:10/Image:195"]');
It's actually a bit of an interesting question. Most likely jQuery thinks :
is initiating a filter, like $('div:visible')
and getting gunked up not realizing it's a full ID.
Upvotes: 7
Reputation: 816780
/
is a meta character, you have to escape it as well:
To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?@[\]^`{|}~
) as a literal part of a name, it must be escaped with with two backslashes:\\
.
So this should work fine:
function escape_selector( selector ) {
return selector.replace( /([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1" );
}
(As roasted mentioned in his comment, you need to drop the '#' +
as well, otherwise you add it twice to the selector).
Upvotes: 2
Reputation: 74420
The simplest answer seems to be:
function jq( myid ) {
return $(document.getElementById(myid));
}
jq(myid).html(...);
Upvotes: 0
Reputation: 26888
The issue is that you're adding the #
twice. Once in the function and once in the actual jQuery
call. Should be like this:
function jq( myid ) {
return "#" + myid.replace( /(:|\.|\/)/g, "\\$1" ); //note that added `/`
}
jQuery(jq(id)).html(SOME HTML HERE); //don't add # again!
A slightly unrelated tip: always remember you can initiate a jQuery instance using an actual DOM object:
jQuery(document.getElementById(someId)); //this will work
Upvotes: 2
Reputation: 1
the correct function is:
function jq( myid ) {
return *$("#" + myid)*.replace( /(:|\.)/g, "\\$1" );
}
jQuery(jq("#"+id)).html(SOME HTML HERE);
Upvotes: -4