Question

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...

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top