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>
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".