(3)選擇元素——(14)接觸DOM元素(Accessing DOM elements)

來源:互聯網
上載者:User

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.


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.