0
0

TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.の解決方法

Posted at

はじめに

fetch した script, css, html を挿入するときに上記のようなエラーが発生したので、その原因と解決方法をまとめます。

発生した問題

まず以下のようなコードでエラーが発生しました。

try {
  const res = (await fetch(url)).json();

  if (res.style) {
    document.head.appendChild(res.style); // ←ここでエラー
  }

} catch (error) {
  console.error("データの取得中にエラーが発生しました:", error);
}

appendChildメソッドはNode.appendChild<HTMLScriptElement>(node: HTMLScriptElement): HTMLScriptElementという定義がなされています。

resはjsonでparseしているのでそのままだとstring型で返ってきます。
そのため、当然HTMLScriptElementではないという型エラーが発生します。

解決方法

解決方法としてはいくつかあるのですが、自分はinsertAdjacentHTMLメソッドを使用することで解決しました。

try {
  const res = (await fetch(url)).json();

  if (res.style) {
    document.head.insertAdjacentHTML('beforeend', res.style);
  }

} catch (error) {
  console.error("データの取得中にエラーが発生しました:", error);
}

insertAdjacentHTMLメソッドとは、string型になっているHTMLやXMLを解釈して、指定した場所に挿入するメソッドです。

まさに今回のようなパターンで使えるメソッドだと思います。

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0