A JavaScript class can not only extend ordinary JavaScript classes, it can extend the DOM class HTMLElement. This allows you to define new types of HTML elements that can be created either directly in HTML or by JavaScript code.

This is illustrated in the two HTML inserts below. In the top one the elements are created directly in HTML as <counted-text> and <count-view> tags. In the bottom one they are created with JavaScript code using the create() methods defined in the CountedText and CountView classes.

In each, the text "Edit me!" is an element of the CountedText class, an extension of HTMLElement. You can edit it freely using the usual select, type characters, backspace, cut, copy, and paste gestures of a GUI text area.

The text "Count = 8." is an element of the CountView class, another extension of HTMLElement. JavaScript code makes it a listener for the CountedText instance, and it displays the character count for that instance.

<a class="html" href="HTMLTextCounting.html" style="width: 100%; height: 8em; background: white;"></a>

<a class="html" href="JSTextCounting.html" style="width: 100%; height: 8em; background: white;"></a>

These examples are described in the menu links to the left.

We want to define a new tag with tag name "counted-text". It could appear in an HTML as follows:

<counted-text id="my-counted-text" text="Edit me!"></counted-text>

The "id" attribute is a standard HTMLElement attribute. The "text" attribute specifies the initial text for the counted-text tag. It will need to be handled in

We also want to be able to construct a <counted-text> tag in JavaScript code. We will use the class name "CountedText" for such objects, defining them in the file CountedText.js. This class will extend the HTMLElement class.

  1. Construct new element contents in a shadow root.
  2. Define the connectedCallback() method to initialize JavaScript values from tag attribute values.
  3. Define getters and setters for new tag attributes.
  4. Specify which attributes are observed.
  5. Define a create() function for construction in JavaScript code.
  6. Register an association between the JavaScript class and the tag name and save a constructor for the class as a static member.

A display of the web page UsingDocumentFragment.html is shown below.

When you add the DocumentFragment fragment to list with the code list.appendChild(fragment) the individual elements of fragment are added to list.