(3)选择元素——(14)接触DOM元素(Accessing DOM elements)
每一个选择器表达式和大部分的jquery方法返回了一个jquery对象。至几乎总是我们想要的,因为它提供了隐式迭代和链锁所用。
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 toanother JavaScript library. Additionally, we might need to access an element's tagname, which is available as a propertyof the DOM element. For these admittedlyrare situations, jQuery provides the .get()method. To access the first DOM elementreferred to by a jQuery object, we would use .get(0). If the DOM element is neededwithin a loop, then we would use .get(index). So, if we want to know the tag nameof an element with id="my-element", we would write 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 followingthe selector:
var myTag = $('#my-element')[0].tagName;
为了更好的便利性,jquery为get()提供了一个快捷方式。我们可以在选择器后面使用中括号,而不用写之前的代码:
var myTag = $('#my-element')[0].tagName;
It's no accident that this syntax appears to treat the jQuery object as an array of DOMelements; using the square brackets is like peeling away the jQuery wrapper to get atthe node list, and including the index(in this case, 0) is like plucking out the DOMelement itself.
毫无意外,这个语法看起来想是我们把jquery对象当成DOM元素数组来看待,使用方括号好像是去到了jquery对象的外包装,然后得到了dom元素列表,包括index(在这里是0),好像是把DOM元素自己扯了出来。