3

In Firebug, when looking at a getElementsByTagName array, which is of type HTMLCollection I see the following functions listed:

  • item()
  • iterator()
  • namedItem()

I know how to use item(number of item) and namedItem(name of item). But what is the use of iterator() ?

I couldn't find an answer, so I'm asking here.

1 Answer 1

2

It's the method JavaScript calls when you iterate over an object using a for…of loop, for instance.

See: http://wiki.ecmascript.org/doku.php?id=harmony:iterators#for-of_loop_bodies

An example:

var myobj = {
  iterator: function() {
    for (let i = 0; i < 5; i++)
      yield i;
  }
}

for (let value of myobj)
  console.log(value);

See also yield.

In case of an HTMLCollection it helps you to write code like:

let divs = document.getElementsByTagName("div");

for (let div of divs) {
  // do something with `div`
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.