Solving `Failed to execute 'importNode' on 'Document'` in Alpine.js
August 12, 2021 ‐ 2 min read
When you encounter the following error you most likely are not using a <template>
tag in a for loop in Alpine.js.
Alpine Expression Error: Failed to execute 'importNode' on 'Document': parameter 1 is not of type 'Node'.
Let's for example consider the following Alpine component.
<div x-data="{ users: ['You', 'Me', 'Someone Else'] }">
<ul x-for="user in users">
<li x-text="user"></li>
</ul>
</div>
At least in Alpine.js version 3 this will show the error as mentioned above and not render any list items. This is due to the fact that x-for
directives should only be declared on <template>
tags, which contain only one root element. So the above example can be fixed as follows:
<ul x-data="{ users: ['You', 'Me', 'Someone Else'] }">
<template x-for="user in users">
<li x-text="user"></li>
</template>
</ul>
The Alpine.js docs define two rules you should keep in mind when using x-for
:
- x-for must be declared on a
<template>
element - That
<template>
element must have only one root element
The <template>
tag is a special HTML5 tag that is not visually rendered on a webpage directly. Instead it is meant to be instantiated with JavaScript once a page is loaded. You can think of it as an elements that just holds content, which you can render dynamically and reuse multiple times if you need to. A side note here is that Internet Explorer does not support the usage of the <template>
tag.