views:

267

answers:

3

Is it just me who find the following code intrinsically backwards?

I am using this posting as a reference.

// create the inner div
var $inner = $("<div>inner</div>")

   // append it to a new outer div
   .appendTo("<div>outer</div>")

   // next change the jQuery chain to the "outer" div 
   .parent()

      // append the outer div to the body
      .appendTo("body")

   // finally, go back to the last destructive command, 
   // giving us back a pointer to the "inner" div
   .end();

My initial approach would have been to grab the body, then append an outer to the body, and then append an inner to the outer.

Approaching it backwards and then jumping around the hierarchy with things like parent () just strikes me as a little curious...

+1  A: 

not really, it all depends what you wish to chain afterwards, using appendTo gives you access to the new element rather than the element you appended to.

redsquare
+2  A: 

The thing with jQuery is, you can do what you like with it. If that particular style doesn't suit you, you don't have to use it.

I find method chaining helps in a lot of cases, but in the particular case you bring up I would do something different - I agree that it's not very clear.

Phill Sacre
+8  A: 

You can do it the other way too:

$('body').append('<div>outer</div>').append('<div>inner<div>');

but that will leave you at body

To end up at inner you'd need to:

$('body').append('<div>outer</div>').append('<div>inner<div>')
.find('div:contains(inner)');
MDCore
jQuery 1.3 changed a bunch of things, so I think the second paragraph may be redundant in that you will automatically end up at div:inner without needing to find.
MDCore