Objective

Create a Counter class to be able to easily create multiple, self-contained, counters in a web page.

Difficulty

Easy

Description

In the previous exercise, JavaScript Exercise — A Simple Counter, you created a counter program that applied to the entire web page (with a global variable count to hold the current count of the counter).

Now, you have to take that very idea one step further and allow the creation of multiple counters, each one self-contained, working with its own count.

In this exercise, you have to construct a Counter class that helps us create a self-contained counter, with its own display and functioning buttons.

What properties and/or methods you need is totally up to you — it's kind of like a mini-test to see how well can you abstract the idea of a counter into a class construct.

The way the class's constructor should work is as follows. It should accept an optional argument which specifies the element node inside which the counter must be placed (as the last child). If the argument isn't provided, it should be taken to be the <body> element.

Shown below is an example of the counter's usage:

<section id="s1" style="border: 1px solid black">
   <h1>Counter 1</h1>
</section>

<section id="s2" style="border: 1px solid black">
   <h1>Counter 2</h1>
</section>
// Assume that Counter has been already defined.

new Counter(document.getElementById('s1'));
new Counter(document.getElementById('s2'));

Live Example