jQuery's End Method

This is a personal reminder, but I hope it may help you too.

I know that nowadays jQuery is not as popular as it used to be.

But sometimes I need to deal with it and I end up forgetting the end() method.

It's pretty simple and very useful. Take a look at this example from jQuery's website:

<ul class="first">
<li class="foo">list item 1</li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>
<ul class="second">
<li class="foo">list item 1</li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>

We need to apply two distinct colors for the items .foo and .bar from ul.first.

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

// or

var selector = $("ul.first")
selector.find(".foo").css("background-color", "red")
selector.find(".bar").css("background-color", "green")

Both the options above get the job done, but we can improve it with end():

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

Here we go down with find, apply the color to .foo and then return with end to the point where we were before (ul.first).

Before you ask me, I tell you, the end() method just goes back one step at a time.

In the following example we need to call it twice to return to our starting point:

<ul class="first">
<li class="foo">list item 1 <a class="another">xD</a></li>
<li>list item 2</li>
<li class="bar">list item 3</li>
</ul>
$("ul.first")
.find(".foo").css("background-color", "red")
.find(".another").css( "background-color", "yellow" )
.end().end()
.find(".bar").css("background-color", "green");

See you.

Written on September 8, 2016

Share: