Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the .end() function do in jQuery?

Tags:

jquery

I have already read this web page http://api.jquery.com/end/ but I am still clueless on what .end() actually does. What is it for and how do you use it?

I am also reading a jQuery book but it lightly glazes over .end() and does not give any examples of what it's for. Can someone clarify?

like image 457
Luke101 Avatar asked Nov 17 '09 00:11

Luke101


3 Answers

$("body").find("span").css("border", "2px red solid");

vs

$("body").find("span").end().css("border", "2px red solid");

Execute these statements separately in Firebug console on this exact page, and notice how different the behaviors are. Basically, .end() tells it to go back to body after finding all spans, and apply the border to body, not the spans. If we don't have the .end() there, the jQuery code basically behaves normally and applies the .css() to our span elements inside of body.

BODY > SPAN > APPLY BORDER TO SPANS

with end() it becomes

BODY > SPAN > GO BACK TO BODY > APPLY BORDER TO BODY

The find() is a destructive operation, meaning it changes what elements are inside of your jquery objects array.

$('body') 

our current element is body

$('body').find('span') 

we used a destructive operation find() which changes our entire objects collection to be populated with spans inside of body, body is no longer in the collection

$('body').find('span').end() 

because find is a "destructive" operation it reverts back to before we did .find(), basically un-does or ctrl-Z's the last thing that changed our jquery collection.

like image 95
meder omuraliev Avatar answered Oct 23 '22 12:10

meder omuraliev


It basically goes back to the parent set. For example:

$('.tree')
    .find('.branch')
        .find('.leaf')
        .addClass('tacks-onto-leaf')
        .end()
    .addClass('tacks-onto-branch')
    .end()
.addClass('tacks-onto-tree');
like image 56
Nick Jurista Avatar answered Oct 23 '22 12:10

Nick Jurista


It backs out the "scope" of a chained JQuery statement to the previous level.

Tags in jQuery object initially [$('P')]: P, P

Tags in jQuery object after find [$('P').find('SPAN')]: SPAN, SPAN, SPAN, SPAN, SPAN

Tags in jQuery object after end [$('P').find('SPAN').end()]: P, P

$('span')              //all <span> tags in the doc
  .find('#foo')          //all <span> with id foo
    .addClass('blinkyRed') //adds class blinkyRed <span id='foo'> 
  .end()                 //reverts scope to all <span> tags
.addClass('Bold')      //adds class Bold to all <span> tags
like image 8
Skeolan Avatar answered Oct 23 '22 11:10

Skeolan