Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is the difference between eq() and get() methods in jQuery ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.48k
    Comment on it

    Hello Readers,

    eq() and get() methods in jQuery:

    eq() method:

    1. eq() method returns the element as a jQuery object.

    2. This method constructs a new jQuery object from one element within that set and returns it that (means you can use jquery functions on it).

    3. eq() method returns jQuery object, means the DOM element is wrapped in the jQuery wrapper, which means that it accepts jQuery functions.

    4. eq(n) retrieves the n-1th jQuery object.

    get() method:

    1. get() method returns a DOM element.

    2. get() method retrives the DOM elements matched by the jquery object.

    3. get() method is not a jquery wrapped object but it is a DOM element.

    4. jQuery functions cant be used in get() method.

    5. .get(n) retrieves the n-1th DOM element. It did be like doing .eq(n)[0].

    Examples of eq() and get() method :

    //Doesn't work
     $("h2").get(0).fadeIn("slow");
    

    above h2 DOM element doesn't have a method called fadeIn.


    //Works
    $("h2").eq(0).fadeIn("slow");
    

    above h2 DOM element have a method called fadeIn (jquery object).

    .get() return a DOM element. So, you may be manipulate it by accessing its attributes and invoking (calling) its functions as you would on a raw DOM element. But it loses its identity as a jQuery-wrapped object, so a jQuery function like fadeIn won't work.

    For Example:

    There is a ul element with 5 li elements.

    <ul>
     <li>list item 1</li>
     <li>list item 2</li>
      <li>list item 3</li>
      <li>list item 4</li>
      <li>list item 5</li>
    </ul>
    

    From the above HTML code to select 3rd <li> element, use either get() or eq() and pass 2 as index. (Keep in mind that index start at zero-based).

    $('li').get(2);
    
    $('li').eq(2);
    

    In the above code, both will return the 3rd <li>element.

    But the difference between the 2 is in code Example:

    $(document).ready(function () {
    
    $('li').eq(2).css('background-color', 'red'); //its Works
    
    $('li').get(1).css('background-color', 'red'); // Error. Object #<HTMLLIElement> has no method 'css'
    
    });
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: