0

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.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
RONE
  • 5,415
  • 9
  • 42
  • 71
  • 2
    Have you looked at the documentation? It provides you with examples. – Blender Aug 26 '13 at 06:42
  • @Blender, dude i have looked and understood the use, but as i said, for me it looks not that important – RONE Aug 26 '13 at 06:44
  • take as case `

    Middle text

    ` then $('p').filter('.middle').find('.i1').css('color', 'red').end().find('.i2').css('color', 'green')` http://plnkr.co/edit/tNWZM5lbWHiqjqQkJ7Yj?p=preview
    – Arun P Johny Aug 26 '13 at 06:45

1 Answers1

0

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

find

filter

Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55