Mootools element.getChildren() Vs element.getElements() – What’s the difference?
I have been writing a fair bit of Javascript recently and came up with a couple of situations where I needed to use Mootools JavaScript element.getChildren() instead of element.getElements() so I thought i’d share a little info which may or may not be obvious about these two very useful Mootools methods.
At first glance of the Mootools documentation, element.getChildren() and element.getElements() look pretty much identical, but what’s not obvious (to me at least) is the fundamental difference between the two methods:
element.getElements() recurses through all child elements from it’s initial starting point whereas element.getChildren() does not, it returns only direct children of the element from which it begins.
For example, if you had a fragment of HTML like this:
<ul id="list_one"> <li>Item one</li> <li>Item two</li> <li> <ul> <li>sub item one</li> <li> sub item two</li> </ul> </li> </ul>
you could then have some JavaScript like this to perform an operation on it:
window.addEvent("domready", function() { var list=$("list_one"); list.getChildren("li").each(function(el, i) { // do something }); });
and that would affect only the 3 immediate children <li> of the outer <ul> and would not affect the “sub items” <li> in the inner <ul>.
NOTE: both element.getChildren() and element.getElements() return an array of DOM elements, hence looping around the result using each().
Conversely, if you wanted to affect all <li> within the outer <ul> you could do something like this:
window.addEvent("domready", function() { var list=$("list_one"); list.getElements("li").each(function(el, i) { // do something }); });
There’s tons more element methods such as element.getFirst() which retrieves the first matching child element.
If you include selectors in your Mootools download, you can add css-style selectors to your methods e.g.:
window.addEvent("domready", function() { var list=$("list_one"); list.getElements("li.some_class").each(function(el, i) { // do something }); });
which would affect only <li> which have a CSS class of “some_class”.
Hope that makes sense and saves someone some time!