开发者

Unable to access dom element using identifier after successfully cloning and appending it

I prepare a clone of a template div, assign it a dynamic ID and append it to DOM, like this:-

var chat_window_clone_obj = $('div#chat_window_template').clone();

cloned_element_id = 'chat_window'+dom_id_separator+session_id;
$(chat_window_clone_obj).attr('id',cloned_element_id);
$(chat_window_clo开发者_StackOverflow社区ne_obj).appendTo("div#chat_windows_holder");

But, after that I am not able access the cloned element using its ID (checked in firefox, I am sure this will be the same in all browsers):-

$('div#chat_windows_holder').length // comes 0
$('div#chat_windows_holder').removeClass("hidden"); //does not work

I am however able to access like this:-

$(chat_window_clone_obj).length // works
$(chat_window_clone_obj).removeClass("hidden"); //works

What am I missing here? I can see the element appended correctly with the required ID in firefox's HTML tab.


When you try selecting it by ID, you're getting the original element - as in the first one which matches that ID. You should not have duplicate IDs in your document. Try this:

var chat_window_clone_obj = $("div#chat_window_template").clone();
chat_window_clone_obj.attr("id", "chat_window_clone");
$("#chat_window_clone").doSomething();


I think the problem is that your not accessing by the correct ID. Is chat_windows_holder the ID of the newly created object? It doesn't look like it is in your sample code.

What is the value of chat_window_clone_obj? That's the value you should be using in your selector (which is why the second example works).


Well guys the problem was that I was using some illegal characters in the dom id which I was assigning to the newly cloned elements.

Something like this -

dom_id_separator = '%%--%%'; //  Character % is illegal

var chat_window_clone_obj = $('div#chat_window_template').clone();
cloned_element_id = 'chat_window'+dom_id_separator+session_id;

Check What characters are allowed in DOM IDs? for list of legal characters.

I was correctly assigning dynamic IDs. I removed the wrapping of chat_window_clone_obj with $() later.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜