Solving `Cannot read property 'cloneNode' of undefined` in Alpine.js
August 11, 2021 ‐ 2 min read
If you are developing with Alpine.js you may encounter the following error at some point:
Alpine Expression Error: Cannot read property 'cloneNode' of undefined
Most likely you are using the x-if
directive on an HTML element other than <template>
. In Alpine.js, the x-if
directive should only be applied on <template>
elements and not on the element you wish to hide or display with conditional rendering.
So let's consider the following element for example.
<h1 x-if="page === ''">Home</h1>
In order to get the above to work properly we need to wrap the h1
in a template
tag. As is shown in the following example:
<template x-if="page === ''">
<h1>Home</h1>
</template>
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.
Alternatively you can possibly use x-show
instead of x-if
if it better suits your use-case. The x-show
directive uses CSS to hide elements and therefore doesn't require the use of the <template>
tag. Alpine does so by setting the display property to "none".