Site Navigation

Wednesday, August 5, 2009

bug 409 - MooTools redundant getElementById(id) method

Issue: #409
Affects: MooTools

If you are developing any web sites or web applications these days you are undoubtedly using a JavaScript Framework or have plans to implement one soon.


This bug is about the MooTools framework, specifically about the Element.getElementById() method.

The docs indicate:
Synopsis: Gets the element with the specified id found inside the current Element.
Example: var myChild = $('myParent').getElementById('myChild');
Notes: This method is not provided for Document instances as document.getElementById is provided natively.


Did you spot it? No? Lets run through it bit by bit.

For starters MooTools uses a very simple $('someID') syntax to get an element by its ID.

Combine that with the fact that the ID attribute of HTML elements must be unique within the document according to the W3C specs... and you've now proven that the .getElementById() method on any other element in the DOM is redundant.

E.g. the above example can also be written as (and in much less code I might add):
Example: var myChild = $('myChild');

Now maybe I'm missing something here that is hidden in the docs that helps explain why verbose, redundant code is somehow helpful or that it provides additional features? If so, please comment and let me know!



Known Workarounds: One. Simply don't use it! Its too bad that the API is cluttered with this extra method but it won't cause any harm to use it.

Example Workaround Code:

var myChild = $('myChild');



When you consider that your JavaScript Framework is providing an API on top of the existing JavaScript/ECMAScript API... you want your Framework API to be as simple and lightweight as possible. Its a minor bug but one that should be addressed to maintain a clean and tight API.

Related Issues: None.

Bug/Site Feedback |
Submit a bug

4 comments:

Adam said...

With document.gid you can only fetch the element if it's appended to the document, so it's not redundant.

Gordon said...

@Adam - thats an interesting observation. I can't say I've ever needed to get an element that isn't attached to the DOM as well, I usually have that variable at hand.

Its too bad the documentation doesn't indicate any of this.

Anonymous said...

I don't buy the un-appended argument at all. I've built dozens of sites using no library, jQuery or Prototype and have never needed to find an element that isn't attached to the document.

I agree with the OP - this method is just cluttering up the mootools api.

coder-zone said...

$('myChild') always selects the element with id=myChild.

$('myParent').getElementById('myChild') only selects id=myChild if is a descendant of myParent.

Is a subtle difference, I know, but there it is.