Tags

Take a look at below HTML. 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>

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…
 
Advertisements