javascript エラー「Uncaught TypeError: xxx.cloneNode is not a function」の解決方法
- 作成日 2022.11.04
- javascript
- javascript

javascriptで、エラー「Uncaught TypeError: xxx.cloneNode is not a function」が発生した場合の原因と解決方法を記述してます。有効でない要素に対して「cloneNode」を使用した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 107.0.5304.88
エラー内容
以下の、class「parent」に「cloneNode」で要素を取得しようとした際に発生。
<div class="parent">
<p class="child">1-1</p>
<p class="child">1-2</p>
</div>
<div class="parent">
<p class="child">2-1</p>
<p class="child">2-2</p>
</div>
<script>
const elm = document.getElementsByClassName('parent');
const result = elm.cloneNode(true);
</script>
エラーメッセージ
Uncaught TypeError: elm.cloneNode is not a function
画像

firefox106の場合でも同じエラーが発生します。
Uncaught TypeError: elm.cloneNode is not a function
画像

safari15.5では、以下のエラーとなります。
TypeError: elm.cloneNode is not a function. (In 'elm.cloneNode(true)', 'elm.cloneNode' is undefined)
画像

原因
有効な要素ではないものに「cloneNode」を使用しているため
解決方法
「getElementsByClassName」で要素を取得している場合は、要素を指定する必要があります。
<div class="parent">
<p class="child">1-1</p>
<p class="child">1-2</p>
</div>
<div class="parent">
<p class="child">2-1</p>
<p class="child">2-2</p>
</div>
<script>
const elm = document.getElementsByClassName('parent');
// trueを指定すると子ノードまで取得されます
const result = elm[0].cloneNode(true);
console.log( result.outerHTML );
</script>
実行結果

もしくは、オブジェクトに「cloneNode」が含まれているか判定してから使用します。
const elm = document.getElementsByClassName('parent');
if (typeof elm === 'object' && elm !== null && 'cloneNode' in elm) {
const result = elm.cloneNode(true);
}
また、存在しない要素を指定すると「Uncaught TypeError: Cannot read properties of undefined (reading ‘cloneNode’)」が発生します。
<div class="parent">
<p class="child">1-1</p>
<p class="child">1-2</p>
</div>
<div class="parent">
<p class="child">2-1</p>
<p class="child">2-2</p>
</div>
<script>
const elm = document.getElementsByClassName('noelm');
const result = elm[0].cloneNode(true);
// Uncaught TypeError: Cannot read properties of undefined (reading 'cloneNode')
console.log( result.outerHTML );
</script>
-
前の記事
kotlin エラー「error: this type is final, so it cannot be inherited from」の解決方法 2022.11.04
-
次の記事
javascript オブジェクトからURLパラメーターを生成する 2022.11.05
コメントを書く