Manaus
Manaus

Reputation: 451

Selecting element from getElements

I have a DOM structure like this:

<article class="detail">
  <img src="img1.jpg" />
  <img src="img2.jpg" />
  <img src="img3.jpg" />
</article>

If I select using

immagini = $$('article.detail').getElements('img')
console.log(immagini[0]) // returns Object { 0: <img>, 1: <img>, 2: <img> }

If I select using

immagini = $$('article.detail img')
console.log(immagini[0]) // returns <img src="img1.jpg" />

I can't understand the difference since, as the Docs say:

getElements collects all descendant elements whose tag name matches the tag provided. Returns: (array) An Elements array of all matched Elements.

Thanks for any explanation

Upvotes: 2

Views: 181

Answers (1)

Sergio
Sergio

Reputation: 28837

When you use $$ you get a array-like collection of article.detail elements. So for each element found getElements will get all img.

This means a mapping of the inicial articles array-like collection you got into arrays of what getElementsfound.

Check this example:

<article class="detail" id="foo">
    <img src="img1.jpg" />
    <img src="img2.jpg" />
    <img src="img3.jpg" />
</article>
<article class="detail" id="bar">
    <img src="img1.jpg" />
    <img src="img2.jpg" />
    <img src="img3.jpg" />
</article>

and the JS/MooTools:

var articles = $$('article.detail')
var img = articles.getElements('img')
console.log(articles, img);

This will print:

[article#foo.detail, article#bar.detail], [Elements.Elements[3], Elements.Elements[3]]

jsFiddle: http://jsfiddle.net/akcvx8gL/

If you want just a array with all img elements you could use the whole selector 'article.detail img' inside $$ like you suggested in your other example or use .flatten() in the end (jsFiddle).

There is a related blog post about this.

"All the methods that MooTools adds to the Element native are added to the Elements class as well. You can do some pretty nifty chaining because of this. This is because any method you call on Elements, will loop through the array and try to call the method on each individual element [...] will return an array of the values from each element.".

Upvotes: 1

Related Questions