jQuery: render element to the DOM, then select it with jquery selector

coffeescript, javascript, jquery

Solution

The reason the first line doesn't work is because element is a string. The reason the second line doesn't work is because it ends up creating another DOM version of the string.

The fix would be to maintain a ref to the DOM version of the element the first time you construct it (in JS):

var $elem = $(element);
$elem.appendTo(document.body);
$elem.hide() // should work

Hope that helps.

Problem

Trying to understand something here: if I render something to the DOM from javascript, and want to call jQuery methods on it, it behaves differently than if I "re-select" the element from the DOM. Here's a simple example, in CoffeeScript: ``` element = """ <div id="my_div">TEST!</div> """ $('body').html(element) element.hide() #this doesn't work. $(element).hide() #this doesn't work either. $('div#my_div').hide() #this does. ``` So, I seem to be misunderstanding something here. I guess the element variable is just a string and jQuery doesn't understand that it has been added as an element in the DOM. Is there a different way to insert content into the dom, then, so that it behaves like a normally-selected jQuery object once it has been inserted?

Original source