jQuery: eq() vs. get()

There are several ways to access queried DOM elements. You get either a DOM element using get() or a jQuery object using eq(). This can be confusing while you try to call jQuery API functions on DOM elements.

The example shows how to get the first array element on three different ways.

<ul>
  <li></li>
  <li></li>
  <li></li>
</ul>

<script type="text/javascript">
    $(document).ready(function(){
        var elems, elem;
        elems = $("li"); // get an array of all the list items

        // This is a jQuery object that you can call jQuery related methods on.
        elem = elems.eq(0); 

        // This is the DOM element itself that lets you access the native
        // javascript attributes and methods.
        elem = elems.get(0); 

        // This is the DOM element too.
        elem = elems[0];
    });
</script>

Instead of using the filter method eq() you can combine the filter with the selector like this

var elem = $("li:eq(0)");

or

var elem = $("li:first");

To turn a DOM element into a jQuery object you can wrap it with jQuery(element) or $(element) if you’re not in conflict mode. But keep in mind that this creates a new object which wastes consumes memory so pay attention if you do this in a loop.

DeliciousDiggTechnorati FavoritesRedditLinkedInFacebookSpurlTwitterWebnewsYiGGMySpaceYahoo BookmarksFriendFeedGoogle BookmarksLiveJournalShare

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>