0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

外部HTMLを読み込んで挿入する方法(JavaScript / fetch )

Last updated at Posted at 2025-09-20

はじめに

表示中のHTMLに、JavaScriptから非同期で別のHTMLを差し込む方法をまとめました。
ネットで情報が少なく、解決に時間がかかったので、同じことで困っている方の参考になれば幸いです。今回は最小単位で、動作するようにまとめました。

動作の流れ

  1. original.html を表示する
  2. JavaScript で input.html を取得する
  3. original.html 内の差し込みたい要素(id)を取得する
  4. その要素を基準に、input.html の中身を DOM に追加する
original.html
<!DOCTYPE html>
<html lang="ja">
<head>
 <script src="fetch.js">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>sample1</title>
</head>
<body>
<div id="contents1">
  <p>これはコンテンツ1です。</p>
</div>

</body>
</html>
input.html
<!DOCTYPE html>
<html lang="ja">
<head>

  <meta charset="UTF-8">
  <title>sample1</title>
</head>

<body>
<div id="content2"></div>
    <p>これはコンテンツ2です。</p>
</div>

</body>
</html>

fetch.js
//関数実行
loadHTML()

async function loadHTML(){
    const response = await fetch("input.html");#差し込みたいHTMLファイル
    const text = await response.text();

    const elem = document.getElementById("contents");
    elem.insertAdjacentHTML('afterend', text);

    console.log(text);
}

出力結果

無事に"input.html"の内容をDOMに差し込む事が出来ました。
result.PNG

参考にした記事

[insertAdjacentHTML:差し込み位置の指定]
(https://qiita.com/amamamaou/items/624c22adec32515e863b)

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?