nickf
nickf

Reputation: 546503

end() function

The end() function in jQuery reverts the element set back to what it was before the last destructive change, so I can see how it's supposed to be used, but I've seen some code examples, eg: on alistapart (which were probably from older versions of jQuery - the article is from 2006) which finished every statement off with .end(). eg:

$( 'form.cmxform' ).hide().end();

Upvotes: 4

Views: 1682

Answers (2)

Luca Rainone
Luca Rainone

Reputation: 16468

From jquery doc there is an example:

$('ul.first').find('.foo')
  .css('background-color', 'red')
.end().find('.bar')
  .css('background-color', 'green')
.end();

and after it a clarification:

The last end() is unnecessary, as we are discarding the jQuery object immediately thereafter. However, when the code is written in this form, the end() provides visual symmetry and a sense of completion —making the program, at least to the eyes of some developers, more readable, at the cost of a slight hit to performance as it is an additional function call.

Upvotes: 0

John Millikin
John Millikin

Reputation: 201056

That end() doesn't do anything. There's no point to coding like that. It will return $('#myBox') -- the example is pretty poor. More interesting is something like this:

$('#myBox').show ().children ('.myClass').hide ().end ().blink ();

Which will show myBox, hide the specified children, and then blink the box. There are more interesting examples here:

http://simonwillison.net/2007/Aug/15/jquery/

such as:

$('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()
    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()
    // add a submit handler to the form
    .submit(function(){
        return confirm('Are you sure you want to submit?');
    });

Upvotes: 5

Related Questions