- Learning jQuery(Fourth Edition)
- Jonathan Chaffer Karl Swedberg
- 216字
- 2021-08-13 17:18:47
Accessing DOM elements
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 element directly. For example, we may need to make a resulting set of elements available to another JavaScript library, or we might need to access an element's tag name, which is available as a property of 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, for example, we would use .get(0)
. So, if we want to know the tag name of an element with an ID of my-element
, we would write:
varmyTag = $('#my-element').get(0).tagName;
For even greater convenience, jQuery provides a shorthand for .get()
. Instead of writing the previous line, we can use square brackets immediately following the selector:
varmyTag = $('#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 layer to get at the node list, and including the index (in this case, 0
) is like plucking out the DOM element itself.
- 零基礎(chǔ)學(xué)Visual C++第3版
- Node.js 10實(shí)戰(zhàn)
- oreilly精品圖書:軟件開發(fā)者路線圖叢書(共8冊)
- Getting Started with Python Data Analysis
- Unreal Engine 4 Shaders and Effects Cookbook
- 微服務(wù)架構(gòu)深度解析:原理、實(shí)踐與進(jìn)階
- Solr Cookbook(Third Edition)
- 計算機(jī)應(yīng)用基礎(chǔ)教程(Windows 7+Office 2010)
- 機(jī)器學(xué)習(xí)微積分一本通(Python版)
- C++程序設(shè)計教程(第2版)
- JBoss AS 7 Development
- SAP HANA Starter
- HTML 5與CSS 3權(quán)威指南(第4版·下冊)
- 交互設(shè)計語言:與萬物對話的藝術(shù)(全兩冊)
- Mastering Docker(Second Edition)