2

I am creating an object dynamically. I am wondering how do I access it? Some of these objects need to be hidden through other means than a click (programmatically, button clicks, links, etc). So I dont think I could use .on. How would I go about accessing these to hide them?

$(document).ready(function() {
$('body').append('<div id="testdiv">Test DIV</div>');

}); 

$('#testdiv').hide();
0

2 Answers 2

5

You reverse your logic. Instead of .append(), you should use .appendTo()

var myRef = $("<div id=\"testdiv\">Test DIV</div>").appendTo( document.body );

That way, you can keep a reference to that newly created DOM node / jQuery object.

myRef.hide();

It's always better to store a cached reference into a variable, so you can access a node from pure ECMA land, so to speak. The need to re-query for a DOM node, is just much less effiecient.

One word of caution: variables declared by var do only own function scope. That means if you want to access that reference from "outside" of your ready handler, you would need to declare that variable in a parent context for instance.

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

4 Comments

... or just chain the hide() after the appendTo().
Should probably clarify that the myRef.hide() cannot be outside doc ready like the op currently has $("#testdiv").hide()
@Esailija: I don't think that is in the scope of this answer (javascript very fundamentals). I don't know the OPs app structure, namespacing, etc.
I agree with @Esailija, just looking at the code in the question. An inference could be made.
2

What you've got already should work, except you'll need to move $('#testdiv').hide(); inside the document ready (so you're not calling it before the element is created).

The other answer is a cleaner way to do it, and the way that I would do it.

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.