1

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_clone_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.

Sandeepan Nath
  • 9,966
  • 17
  • 86
  • 144
  • Why are you wrapping chat_window_clone_obj in $()? –  Mar 24 '11 at 12:41
  • 1
    you shouldn't wrap `chat_window_clone_obj` with `$()` because it will clone the object each time you do so. That means i.e. `$(chat_window_clone_obj).attr('id',cloned_element_id);` should be `chat_window_clone_obj.attr('id',cloned_element_id);` – thwd Mar 24 '11 at 12:48
  • 1
    Thanks @Tom can you give some explanation or some link explaining that – Sandeepan Nath Apr 20 '11 at 14:27

3 Answers3

2

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();
karim79
  • 339,989
  • 67
  • 413
  • 406
0

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).

jjross
  • 678
  • 1
  • 6
  • 19
0

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.

Community
  • 1
  • 1
Sandeepan Nath
  • 9,966
  • 17
  • 86
  • 144