Reputation: 5485
I have looked in to the jquery documentation of function end(),
definition : End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
i have understood the functionality, but i could not able to make out, where it is more helpful.
ex:
<p>text</p>
<p class="middle">Middle <span>text</span></p>
<p>text</p>
<script type="text/JavaScript">
alert(jQuery('p').filter('.middle').length); //alerts 1
alert(jQuery('p').filter('.middle').end().length); //alerts 3
alert(jQuery('p').filter('.middle').find('span')
</script>
i have understood the second line displaying //alerts 3
, but it can also be written as
alert(jQuery('p').length); //alerts 3
Then why extra two methods .filter
and .end()
,
please give me an example, where the .end() will be useful.
Upvotes: 0
Views: 146
Reputation: 10378
HTML
<p>text</p>
<p class="middle">Middle <span>text</span></p>
<p>text</p>
in this p tag as sibling element
and pwith class "middle" has child tag which is "span" tag
now talk about your js
<script type="text/JavaScript">
/*it display 1 and its right first we find p tag then in this we filter by "middle class"
and in p tag only one have this class so alert 1
*/
alert(jQuery('p').filter('.middle').length);
/*it display 3 and its right first we find p tag then in this we filter by "middle class" then again use end inn jquery then it again goes to previous selector means
(jQuery('p').filter('.middle') to jQuery('p')
so it alert 3
*/
alert(jQuery('p').filter('.middle').end().length); //alerts 3
/*it display 3 and its right first we find p tag then in this we filter by "middle class" then again use find span and it has one span in middle class so it alert 1
*/
alert(jQuery('p').filter('.middle').find('span').length); alert 1
</script>
reference end
Upvotes: 0