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. get () method. to access the first DOM element referred to by a jQuery object, we wocould use. get (0 ). if the DOM element is needed within a loop, then we wocould use. get (index ). so, if we want to know the tag name of an element with id = "my-element", we wocould write the following code snippet:
Var myTag = $ ('# my-element'). get (0). tagName;
However, there are some areas in our code that we want to access DOM elements. For example, we may want to make a series of elements available for other js libraries. In addition, we may need to access the name of an element, which can be achieved by using the attributes of the DOM element. Jquery provides the. get () method that can be referenced by jquery objects for these rarely recognized scenarios. We will use. get (0 ). If the DOM element is needed in a loop, we will use. get (index ). Therefore, if we want to know that id is the name of the element of my-element, we will use the following code snippet: 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.