Every selector expression and most jQuery methods return a jQuery object. This is almost always what we want, because of the implicit iteration and chaining capabilities that it affords.
Still, there may be points in our code when we need to access a DOM elementdirectly. For example, we may need to make a resulting set of elements available to another JavaScript library. Additionally, we might need to access an element's tag name, which is available as a propertyof the DOM element. For these admittedly rare situations, jQuery provides the .get()method. To access the first DOM element referred to by a jQuery object, we would use .get(0). If the DOM element is needed within a loop, then we would use .get(index). So, if we want to know the tag name of an element with id="my-element", we would write the following code snippet:
var myTag = $('#my-element').get(0).tagName;
然而在我們的代碼中還有有一些地方我們想要接觸到DOM元素。比如,我們可能想讓一系列元素可以讓其他的js庫使用。另外,我們可能需要接觸到一個元素的名字,使用DOM元素的屬性可以做到這一點。對這些公認很少出現的情境,jquery提供了.get()方法可以由jquery對象引用。我們將使用.get(0)。如果DOM元素是在一個迴圈中被需要的,我們將使用.get(index)。因此,如果我們想要知道id是my-element的元素的名字,我們將使用下面的程式碼片段:var myTag=$("#my-element").get(0).tagName;
For even greater convenience, jQuery provides a shorthand for .get(). Instead of writing the preceding line, we can use square brackets immediately following the selector:
var myTag = $('#my-element')[0].tagName;
It's no accident that this syntax appears to treat the jQuery object as an array of DOM elements; using the square brackets is like peeling away the jQuery wrapper to get at the node list, and including the index(in this case, 0) is like plucking out the DOM element itself.