2

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

I think you need:

element = $('<div id="my_div">TEST!</div>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.