- MooTools 1.3 Cookbook
- Jay Larry G. Johnston
- 312字
- 2021-04-02 19:07:07
Finding an element by its ID attribute
This cross-browser method allows us to quickly get a "handle" on our HTML element.
How to do it...
If we imagined a world where we could grab an element with a simple and easy-to-remember syntax just by sending the element's ID attribute, we would be dreaming of MooTools.
<script type="text/javascript"
src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="my_trigger"
style="width:100px; height:100px;
border:1px solid #BEBEBE;
line-height:50px; text-align:center;">You Found Me!</div> <noscript>JavaScript is disabled.</noscript>
Tip
Always include the NOSCRIPT tag, which is omitted going forward only to save space.
<script type="text/javascript"> // raw javascript's familiar method, not cross-browser use // var my_element = document.getElementByID('my_target'); // MooTools uses the $ object to grab elements by ID var my_element = $('my_trigger'); var my_element_text = my_element.get('text'); alert(my_element_text); </script>
Tip
Always include the closing BODY and HTML tags. Also omitted going forward.
</body> </html>
How it works...
When we use raw JavaScript to get a handle on an element, we either depend on the browser to match our code, or we have to write a mess of browser compatibility to be sure that our user has a browser that supports the JavaScript implementation that we are writing for. MooTools abstracts that cross-browser nightmare and gives us the dollar object $()
, an alias for document.id()
.
Note
Starting with version 1.2, MooTools began to use document.id()
to grab elements by ID. This allows MooTools to play nice with other frameworks that extend using the dollar syntax. When using multiple frameworks, do not use the $()
alias for document.id()
.
Pass the dollar or document.id()
object the ID for the element to grab, and the object returned is a MooTools-extended object ready to do our bidding through Element methods.
In this example, we use the method get()
, which takes a single argument, the property of the object to return. We then alert the var my_element_text
to the screen using the raw JavaScript alert()
function.
There's more...
This recipe can be easily recreated with a single, easy-to-understand one-liner:
alert($('my_trigger').get('text'));
- 中文版Photoshop入門與提高(CS6版)
- 四時風(fēng)月繪:國風(fēng)水墨CG插畫繪畫技法
- UI 設(shè)計入門一本就夠
- 中文版Photoshop 2020基礎(chǔ)教程
- 碼上學(xué)會:中文版Creo 3.0機(jī)械設(shè)計全能一本通(雙色版)
- 中文版Photoshop 2022基礎(chǔ)教程
- Refactoring with Microsoft Visual Studio 2010
- Instant Markdown
- Excel 2010 Financials Cookbook
- 中文版CorelDRAW X7技術(shù)大全
- Mobile Web Development
- AutoCAD 2019中文版完全自學(xué)手冊(標(biāo)準(zhǔn)版)
- Oracle Modernization Solutions
- AutoCAD快速自學(xué)寶典(2019中文版)
- Pluggable Authentication Modules: The Definitive Guide to PAM for Linux SysAdmins and C Developers