Reputation: 34188
i go to the site http://api.jquery.com/end/ just to understand how end() use and how it works. unfortunately i just do not understand what it does. so i need to know in what kind of situation end() should be used.
<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>
$('ul.first')
.find('.foo')
.css('background-color', 'red')
.end()
.find('.bar')
.css('background-color', 'green');
i just do not understand what kind of role end()
function play here.
it would be great if someone help me to understand the usage of end()
function with small & easy sample code. please help. thanks
Upvotes: 0
Views: 671
Reputation: 11931
Description: End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
Ill explain $('ul.first').find('.foo').css('background-color', 'red')
.end().find('.bar').css('background-color', 'green');
. You select all the ul.first
elements, and select all the .foo
elements from there (and change the BG color). Next, you end the sequence, so you 'undo' your search for .foo
elements.
Now you search for all the .bar
elements, and change their BG color.
The function of end()
is to stop the sequence of searches, and go up one level of searching. In the example, if there was no end()
, there would be no .bar
elements, because there is no ul.first .foo .bar
element in the HTML.
Upvotes: 0
Reputation: 38345
The initial selector returns all ul
elements with the class first
. The .find('.foo')
returns all children of those elements with the class foo
, then sets a background-color of red to them. The use of .end()
returns the previous set of elements prior to the .find()
- so, again, all ul
elements with the class first
- then looks for children with the class bar
.
Upvotes: 2
Reputation: 385144
This is explained pretty well in the documentation:
End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
It's clearer if I render the code like so:
$('ul.first')
.find('.foo')
.css('background-color', 'red')
.end()
.find('.bar')
.css('background-color', 'green');
It means that what you're setting background-color
to green
on is ul.first .bar
, not ul.first .foo .bar
. It undoes the .find('foo')
filter in that call chain.
An equivalent would be:
$('ul.first').find('.foo').css('background-color', 'red');
$('ul.first').find('.bar').css('background-color', 'green');
Upvotes: 2