End ()

The end() function in jQuery returns the element returned to what it was before the last destructive change, so I can see how it should be used, but I saw code examples, for example: on alistapart (probably from earlier versions of jQuery - article since 2006), which completed each statement with .end() . eg:

 $( 'form.cmxform' ).hide().end(); 
  • Does this have an effect?
  • Is that what I have to do?
  • What returns the code above?
+4
source share
2 answers

That end() does nothing. There is no point in coding. It will return $('#myBox') - the example is rather poor. More interesting is something like this:

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

myBox will be displayed, hide the specified children, and then blink. There are more interesting examples here:

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

eg:

 $('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?'); }); 
+5
source

From jquery doc an example is given:

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

and after it clarification:

The last end () is not needed as we immediately discard the jQuery object. However, when the code is written in this form, end () provides visual symmetry and a sense of completion - creating a program, at least for the eyes of some developers, is more readable, due to a small impact on performance, as this is an additional function call.

0
source

Source: https://habr.com/ru/post/1277430/


All Articles