views:

81

answers:

1

I am working on a personal project involving some jQuery / native Javascript programming. I am hoping somebody can clarify an issue I'm seeing with my code. I'm confused about the relationship among objects created in Javascript and objects that are part of the DOM.

When using JQuery UI (the tabs feature), my program behaves differently depending on whether I manipulate my object from Javascript directory, or if I first access it from the DOM API, which leads me to believe that the two references are not equal.

For Example:

myObject = $(document.createElement("div")).attr("id", "tabs");
$("body").append(myObject);

Now, I have found that the following example works correctly:

$("#tabs").tabs();

But the following does not:

$(myObject).tabs();

Am I correct in assuming that the object I am retrieving via $("#tabs") is different or works different than the object I have created manually in Javascript (myObject)?

Is there some mechanism that is invoked once you insert an object into the DOM? Should I not be tinkering with it after I insert it into the DOM, and instead re-retrieve it via its id field?

+5  A: 

Creating elements with the raw JS methods is no different to any element referenced with jQuery except that those found by expressions like $(...) are wrapped in a jquery object.

Since you're doing this:

myObject = $(document.createElement("div")).attr("id", "tabs");

you already have a jquery object so you should be able to do this:

myObject.tabs();

By doing:

$(myObject).tags();

you're effectively doing this:

$($(document.createElement(...)...);

and I'm not sure what the expected behaviour of that is.

Also bear in mind you can do this (and should favour this way):

var myObject = $("<div></div>").attr("id", "tabs");

The var makes it local in scope (which is what you want 95% of the time) and you can create arbitrary markup with jquery without using the raw JS methods.

cletus
Would love to know why this was downvoted...
cletus
+1 for `var` and simplified element creation. Don't see why this was down-voted.
Justin Johnson
cool, thanks for the advice. I like the $("<div></div>) approach. Is it valid to do this? $("<div id='someID' class='someClass'></div>")
darren
@darren: yes its valid but (imho) not recommended in non-trivial cases because if, say, you include dynamic text it may not be correctly escaped, etc whereas the attr() methods (etc) will correctly escape content and ensure the HTML is valid.
cletus