Using LinkeDOM with Deno

LinkeDOM is a DOM-like namespace to be used in environments, like Deno, which don’t implement the DOM.

LinkeDOM focuses on being fast and implementing features useful for server side rendering. It may allow you to do things that are invalid DOM operations. deno-dom and jsdom focus on correctness. While currently deno-dom is slower than LinkeDOM in some cases, both are significantly faster than jsdom, so if you require correctness or features not related to server side rendering, consider deno-dom.

While LinkeDOM works under the Deno CLI, it does not type check. While the provided types work well when using an editor like VSCode, attempting to strictly type check them, like Deno does by default, at runtime, it will fail. This is the same if you were to use tsc to type check the code. The maintainer has indicated they aren’t interested in fixing this issue. This means for Deno, you need to use the --no-check=remote to avoid diagnostics stopping the execution of your programme.

LinkedDOM runs under Deno Deploy, along with deno_dom, but jsdom does not.

Basic example

This example will take a test string and parse it as HTML and generate a DOM structure based on it. It will then query that DOM structure, picking out the first heading it encounters and print out the text content of that heading:

  1. import { DOMParser } from "https://esm.sh/linkedom";
  2. import { assert } from "https://deno.land/std@0.132.0/testing/asserts.ts";
  3. const document = new DOMParser().parseFromString(
  4. `<!DOCTYPE html>
  5. <html lang="en">
  6. <head>
  7. <title>Hello from Deno</title>
  8. </head>
  9. <body>
  10. <h1>Hello from Deno</h1>
  11. <form>
  12. <input name="user">
  13. <button>
  14. Submit
  15. </button>
  16. </form>
  17. </body>
  18. </html>`,
  19. "text/html",
  20. );
  21. assert(document);
  22. const h1 = document.querySelector("h1");
  23. assert(h1);
  24. console.log(h1.textContent);

Alternative API

For the parseHTML() can be better suited for certain SSR workloads. This is similar to jsdom’s JSDOM() function, in the sense it gives you a “sandbox” of a window scope you can use to access API’s outside of the scope of the document. For example:

  1. import { parseHTML } from "https://esm.sh/linkedom";
  2. const { document, customElements, HTMLElement } = parseHTML(`<!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <title>Hello from Deno</title>
  6. </head>
  7. <body>
  8. <h1>Hello from Deno</h1>
  9. <form>
  10. <input name="user">
  11. <button>
  12. Submit
  13. </button>
  14. </form>
  15. </body>
  16. </html>`);
  17. customElements.define(
  18. "custom-element",
  19. class extends HTMLElement {
  20. connectedCallback() {
  21. console.log("it works 🥳");
  22. }
  23. },
  24. );
  25. document.body.appendChild(document.createElement("custom-element"));
  26. document.toString(); // the string of the document, ready to send to a client