DOM Element Types: What They Are and How to Use Them

The Document Object Model (DOM) is a tree-like representation of the HTML document that allows us to access and manipulate its elements using JavaScript. Elements are the building blocks of the DOM tree, and they can have different types, categories, and roles depending on their attributes and content.

In this article, we will explore the various element types in the DOM and how to work with them using JavaScript. We will cover the following topics:

  1. HTML Elements: The most common type of elements in the DOM that are defined by HTML tags.
  2. SVG Elements: A type of elements in the DOM that represent Scalable Vector Graphics (SVG) using XML syntax.
  3. Custom Elements: A type of elements in the DOM that allow us to define and use our own custom tags and behaviors.

HTML Elements

HTML elements are the most common type of elements in the DOM. They are defined by a start tag, an end tag, and optionally some attributes and content. For example, <p id="intro">This is a paragraph.</p> is an HTML element that represents a paragraph of text. HTML elements can be nested inside other HTML elements to create complex structures.

Block-level Elements and Inline Elements

HTML elements can be divided into two main categories: block-level elements and inline elements.

  1. Block-level elements occupy the entire width of their parent element and create a new line before and after themselves.
  2. Inline elements only occupy the space needed for their content and do not create new lines.

Examples of block-level elements are <div>, <p>, <h1>-<h6>, <ul>, <ol>, <table>, etc. Examples of inline elements are <span>, <a>, <img>, <em>, <strong>, etc.

Accessing HTML Elements

We can access HTML elements in the DOM using various methods, such as:

  • getElementById(): Returns a single element that has the specified id attribute.
  • getElementsByClassName(): Returns a collection of elements that have the specified class attribute.
  • getElementsByTagName(): Returns a collection of elements that have the specified tag name.
  • querySelector(): Returns the first element that matches the specified CSS selector.
  • querySelectorAll(): Returns a collection of elements that match the specified CSS selector.

These methods return either a single element or a collection of elements that match the specified criteria. For example, document.getElementById("intro") returns the <p> element with the id attribute of "intro", while document.getElementsByTagName("p") returns a collection of all <p> elements in the document.

You can check out our detailed guide to learn how to select specific html elements.

How to Create HTML Elements

We can also create new HTML elements in the DOM using the createElement() method. This method takes a string argument that specifies the tag name of the element and returns a new element object that can be appended to the DOM tree using methods such as:

  • appendChild(): Appends a new child element to the end of the parent element.
  • insertBefore(): Inserts a new child element before an existing child element of the parent element.
  • replaceChild(): Replaces an existing child element with a new child element of the parent element.
  • removeChild(): Removes an existing child element from the parent element.

For example, let newDiv = document.createElement("div") creates a new <div> element that can be added to the document body using document.body.appendChild(newDiv).

SVG Elements

SVG elements are another type of elements in the DOM that represent Scalable Vector Graphics (SVG). SVG is a language for describing two-dimensional graphics using XML syntax. SVG elements can be embedded inside HTML documents using the <svg> element or referenced externally using the <img> element or the background-image CSS property. SVG elements can also be created dynamically using JavaScript and the createElementNS() method.

SVG Namespace and Attributes

SVG elements have some differences from HTML elements, such as:

  • SVG elements use a different namespace than HTML elements, which means they need to be created using the createElementNS() method instead of the createElement() method. The namespace for SVG elements is http://www.w3.org/2000/svg.
  • SVG elements have different attributes and properties than HTML elements, such as x, y, width, height, fill, stroke, transform, etc. These attributes and properties can be accessed and modified using the getAttribute(), setAttribute(), getAttributeNS(), setAttributeNS(), style property, etc.

SVG Element Types and Categories

SVG elements have different types and categories than HTML elements, such as:

  • <circle>: Draws a circle with a given center and radius.
  • <rect>: Draws a rectangle with a given position, width, and height.
  • <path>: Draws a complex shape using a series of commands and coordinates.
  • <text>: Draws a text string with a given position and style.
  • <g>: Groups multiple elements together and applies transformations or styles to them.
  • <defs>: Defines reusable elements that can be referenced by other elements.
  • <use>: References an element defined by <defs> and draws a copy of it.

These types and categories define the shape, appearance, and behavior of the SVG elements.

For example, the following code creates a new SVG element that draws a red circle with a black border and appends it to the document body:

JAVASCRIPT
                        
// create a new SVG element
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
// set the width and height attributes
svg.setAttribute("width", "100");
svg.setAttribute("height", "100");
// create a new circle element
let circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
// set the cx, cy, r, fill, and stroke attributes
circle.setAttribute("cx", "50");
circle.setAttribute("cy", "50");
circle.setAttribute("r", "40");
circle.setAttribute("fill", "red");
circle.setAttribute("stroke", "black");
// append the circle to the SVG element
svg.appendChild(circle);
// append the SVG element to the document body
document.body.appendChild(svg);

Custom Elements

Custom elements are a type of elements in the DOM that allow us to define and use our own custom tags and behaviors. Custom elements are part of the Web Components standard, which also includes Shadow DOM, HTML templates, and HTML imports. Custom elements can extend existing HTML elements or create new ones from scratch.

Defining and Registering Custom Elements

To create a custom element, we need to follow these steps:

  • Define a class that extends the HTMLElement class or one of its subclasses, such as HTMLButtonElement, HTMLInputElement, etc. This class defines the properties, methods, and lifecycle callbacks of the custom element.
  • Register the custom element using the customElements.define() method. This method takes two arguments: the name of the custom element and the class that defines it. The name of the custom element must contain a hyphen, such as <my-button>, <my-input>, etc.

For example, the following code defines a custom element that extends the <button> element and adds a click counter:

JAVASCRIPT
                        
// define a class that extends the HTMLButtonElement class
class MyButton extends HTMLButtonElement {
  // define a constructor that calls the super constructor and initializes the counter
  constructor() {
    super();
    this.counter = 0;
  }
  // define a connectedCallback that adds a click event listener to the button
  connectedCallback() {
    this.addEventListener("click", () => {
      // increment the counter and display it on the button
      this.counter++;
      this.textContent = You clicked me ${this.counter} times;
    });
  }
}
// register the custom element using the customElements.define() method
customElements.define("my-button", MyButton, { extends: "button" });

Using Custom Elements

To use the custom element, we can either write it in the HTML document using the is attribute, such as <button is="my-button">Click me</button>, or create it dynamically using JavaScript, such as let myButton = new MyButton().

Summary

In this article, we have learned about the different element types in the DOM and how to work with them using JavaScript. We have seen that elements can be categorized into HTML elements, SVG elements, and custom elements, and that each type has its own characteristics, attributes, and methods. We have also learned how to access, create, and manipulate elements in the DOM using various methods and techniques. We hope that this article has helped you understand the DOM better and enhance your web development skills.