ios85
ios85

Reputation: 2134

How to access a dynamically created object

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();

Upvotes: 2

Views: 98

Answers (2)

jAndy
jAndy

Reputation: 236022

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.

Upvotes: 5

Bennor McCarthy
Bennor McCarthy

Reputation: 11675

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.

Upvotes: 2

Related Questions