Wednesday 24 April 2013

Difference between eq() and get()


Both the methods are used to find and select single element from set of elements and they both return single "element". And they both accept single int type parameter, which denotes index.

For example, take a look at below HTML. There is a <ul> element with 5 <li> elements.

<ul>
    <li>Test1</li>
    <li>Test2</li>
    <li>Test3</li>
    <li>Test4</li>
    <li>Test5</li>
</ul>

And to select 3rd <li> element, use either get() or eq() and pass 2 as index. Keep in mind that index is zero-based.

$('li').get(2);
$('li').eq(2);
In the above code, both will return the 3rd <li> element. But then what is the difference between 2.

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

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used. 

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

Good Luck...

No comments:

Post a Comment