Skip to content

HTMLTemplateElement.insertBefore() redirects to template.content instead of adding direct children #1961

@ianlet

Description

@ianlet

Describe the bug
Calling insertBefore() on an HTMLTemplateElement appears to redirect the node to template.content instead of adding it as a direct child. This differs from browser behavior where insertBefore() adds direct children to the template element itself.

To Reproduce

const template = document.createElement('template');
const div = document.createElement('div');
template.insertBefore(div, null);

console.log(template.childNodes.length);         // happy-dom: 0
console.log(template.content.childNodes.length); // happy-dom: 1

Expected behavior
Based on Firefox (and jsdom), insertBefore() should add the node as a direct child:

console.log(template.childNodes.length);         // Expected: 1
console.log(template.content.childNodes.length); // Expected: 0

Firefox console output

template.insertBefore(div, null);
console.log(template.childNodes.length); // Output: 1
console.log(template.content.childNodes.length); // Output: 0

Device:

  • OS: Linux
  • happy-dom version: 20.0.11
  • Compared against: Firefox, jsdom 26.1.0

Additional context
This may be an intentional design choice rather than a bug - perhaps enforcing the template content model more strictly. However, it causes compatibility issues with libraries that use template elements as generic containers for temporary DOM storage (e.g., Qwik's VirtualElementImpl), which work fine in real browsers.

We discovered this while trying to add support for happy-dom in Qwik Testing Library. Here's the workaround we implemented in the meantime: Add happy-dom support for Qwik Testing Library

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions