リンクを要素として作る
前の節で、URL の組み立ては URLSearchParams に任せました。
同じ考えを、リンクを作っている部分にも当てます。
この節で作るもの
Section titled “この節で作るもの”動きは前の節と同じです。何度押してもリンクが1本のままであることを確かめてください。
今回さわるファイル:
index.htmlの出力部分を書き換える
前の節を終えていない人は、ここから始められます。
文字列でタグを組み立てている
Section titled “文字列でタグを組み立てている”いまリンクを作っているのはこの1行です。
result.innerHTML = '<a href="' + url + '" target="_blank">' + url + '</a>';やっていることは、前の節でやめたのと同じ「文字列の足し算」です。
引用符の開き閉じ、> の位置、閉じタグ。どれも自分で正しく並べる必要があります。
innerHTML は渡された文字列をタグとして解釈するので、組み立てを1か所でも間違えると、
表示が崩れたり、意図しないタグが差し込まれたりします。
createElement で <a> を作る
Section titled “createElement で <a> を作る”文字列ではなく、要素そのものを作ります。
const link = document.createElement('a');document.createElement('a') は、新しい a 要素を1つ作って返します。
getElementById がすでにあるものを探すのに対して、createElement は新しく作る命令です。
作った時点では、まだどこにも置かれていないので画面には出ません。
setAttribute で href と target を付ける
Section titled “setAttribute で href と target を付ける”属性は setAttribute(属性名, 値) で足します。
link.setAttribute('href', url);link.setAttribute('target', '_blank');文字列で書いていたときは、'<a href="' + url + '"' のように引用符を自分で閉じていました。
setAttribute なら値を渡すだけで、引用符の開き閉びを気にする必要がありません。
中身を入れ替える
Section titled “中身を入れ替える”リンクに表示する文字を入れて、出力先に差し込みます。
index.html を変更する
Section titled “index.html を変更する”105105 const url = 'docs.html?' + params.toString();106106
107 result.innerHTML = '<a href="' + url + '" target="_blank">' + url + '</a>';107 // リンクも文字列で組み立てるのをやめ、要素として作る。108 const link = document.createElement('a');109 link.setAttribute('href', url);110 link.setAttribute('target', '_blank');111 link.textContent = url;112
113 // 前に作ったリンクが残らないように、中身を空にしてから入れる。114 result.textContent = '';115 result.append(link);108116 });109117 </script>110118</body>append は、要素の中に別の要素を追加する命令です。追加なので、
result.textContent = '' で空にしておかないと、押すたびにリンクが下に増えていきます。
コラム: innerHTML に入力値を混ぜると
Section titled “コラム: innerHTML に入力値を混ぜると”この節の書き換えは、見た目も動きも変わりません。では何が変わったのか。
下のデモは、同じ入力文字を innerHTML に文字列で渡した場合と、
createElement と textContent で入れた場合を並べたものです。
件名に <b>至急</b> 月次報告 と入れると、上は「至急」が太字になります。
入力された文字がタグとして解釈されたからです。下はそのまま文字として出ます。
<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <title>innerHTML と createElement の違い</title> <style> body { font-family: "Segoe UI", "Meiryo", sans-serif; line-height: 1.7; margin: 16px; }
input { width: 22em; }
h2 { font-size: 1em; margin: 1.2em 0 0.3em; }
.out { background: #f3f3f3; padding: 8px 10px; min-height: 1.7em; }
.note { color: #555; margin: 0.3em 0 0; } </style> </head> <body> <p> 件名 <input id="title" value="<b>至急</b> 月次報告" /> </p>
<h2>innerHTML に文字列で渡した場合</h2> <div id="byInnerHtml" class="out"></div> <p class="note">入力した文字がタグとして解釈され、表示が変わってしまいます。</p>
<h2>createElement で要素として作った場合</h2> <div id="byCreateElement" class="out"></div> <p class="note">入力した文字がそのまま文字として出ます。</p>
<script> const titleInput = document.getElementById('title'); const byInnerHtml = document.getElementById('byInnerHtml'); const byCreateElement = document.getElementById('byCreateElement');
function update() { // 文字列としてタグを組み立てる書き方。 byInnerHtml.innerHTML = '件名は「' + titleInput.value + '」です';
// 要素を作り、文字は textContent で入れる書き方。 byCreateElement.textContent = ''; byCreateElement.append('件名は「'); const strong = document.createElement('span'); strong.textContent = titleInput.value; byCreateElement.append(strong); byCreateElement.append('」です'); }
titleInput.addEventListener('input', update); update(); </script> </body></html>いまの index.html は URLSearchParams を通した url だけを渡しているので、
この問題は起きません。ただし「文字列でタグを組み立てる」書き方を続ける限り、
どこか1か所で変換を忘れたときに同じことが起こります。
要素として作れば、入力された値は常に文字としてしか扱われません。 気をつけて書く必要そのものが無くなります。
前の節と同じように、生成したリンクを押すと docs.html が開けば成功です。
何度押してもリンクが1本のままであることも確かめてください。
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”<!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <title>資料検索(受け取り側)</title> <style> body { font-family: "Segoe UI", "Meiryo", sans-serif; line-height: 1.7; margin: 24px; } table { border-collapse: collapse; } th, td { border: 1px solid #999; padding: 4px 10px; text-align: left; } th { background: #e2efda; } .note { color: #555; } .url { word-break: break-all; } </style> </head> <body> <h1>資料検索(受け取り側)</h1>
<p class="note"> 検索システムの代わりに置いてある、受け取ったパラメータを並べるだけのページです。 実際に使うときは、ここが本物の検索システムのURLに変わります。 </p>
<p>受け取ったURL:<span id="url" class="url"></span></p>
<h2>受け取ったパラメータ</h2>
<table> <thead> <tr> <th>キー</th> <th>値</th> </tr> </thead> <tbody id="rows"></tbody> </table>
<p id="empty" class="note" hidden>パラメータは1つも付いていません。</p>
<script> const url = document.getElementById('url'); const rows = document.getElementById('rows'); const empty = document.getElementById('empty');
url.textContent = location.href;
// location.search は「?」から後ろの文字列。 // 受け取る側も URLSearchParams で読み解くのがいちばん簡単。 const params = new URLSearchParams(location.search);
let count = 0;
params.forEach((value, key) => { const row = document.createElement('tr'); const keyCell = document.createElement('td'); const valueCell = document.createElement('td');
keyCell.textContent = key; valueCell.textContent = value;
row.append(keyCell, valueCell); rows.append(row);
count = count + 1; });
if (count === 0) { empty.hidden = false; } </script> </body></html><!doctype html><html lang="ja"> <head> <meta charset="utf-8" /> <title>資料検索のURLを作る</title> <style> table { border-collapse: collapse; }
th, td { border: 1px solid #999; padding: 4px 10px; text-align: left; }
th { background: #e2efda; } </style> </head> <body> <h1>資料検索のURLを作る</h1>
<table> <thead> <tr> <th>項目</th> <th>パラメータ名</th> <th>値</th> <th>参考値</th> </tr> </thead> <tbody> <tr> <td>部署コード</td> <td>dept</td> <td><input id="dept" /></td> <td>25、ALL</td> </tr> <tr> <td>件名</td> <td>title</td> <td><input id="title" /></td> <td>月次報告</td> </tr> <tr> <td>作成者</td> <td>author</td> <td><input id="author" /></td> <td>山田</td> </tr> <tr> <td>作成日</td> <td>date</td> <td><input id="date" /></td> <td>2026-04-01</td> </tr> </tbody> </table>
<p> <button id="generateButton">生成</button> </p>
<p> 生成されたURL:<span id="result"></span> </p>
<script> const deptInput = document.getElementById('dept'); const titleInput = document.getElementById('title'); const authorInput = document.getElementById('author'); const dateInput = document.getElementById('date'); const generateButton = document.getElementById('generateButton'); const result = document.getElementById('result');
generateButton.addEventListener('click', () => { // 部署コードが無いと検索システム側がエラーになるので、ここで止める。 if (deptInput.value === '') { alert('部署コードは必須です。'); return; }
// クエリ文字列を組み立てる道具。 // 「&」でつなぐのも、空白や日本語の変換も URLSearchParams がやってくれる。 const params = new URLSearchParams();
if (deptInput.value !== '') { params.append('dept', deptInput.value); }
if (titleInput.value !== '') { params.append('title', titleInput.value); }
if (authorInput.value !== '') { params.append('author', authorInput.value); }
if (dateInput.value !== '') { params.append('date', dateInput.value); }
const url = 'docs.html?' + params.toString();
// リンクも文字列で組み立てるのをやめ、要素として作る。 const link = document.createElement('a'); link.setAttribute('href', url); link.setAttribute('target', '_blank'); link.textContent = url;
// 前に作ったリンクが残らないように、中身を空にしてから入れる。 result.textContent = ''; result.append(link); }); </script> </body></html>