見てみよう:すべての呪文の3ステップ
JavaScript がページでやることのほとんどは3ステップ:
- ページ上の 要素を見つける(ボタン、見出し、画像…)、
- イベントを待つ(クリック、マウスホバー、文字入力…)、
- 何かする(テキスト変更、色変更、非表示、表示…)。
コードではこう。HTML にボタンと段落を追加:
<button id="my-button">Click me</button>
<p id="greeting">Nothing has happened yet.</p>
script.js では:
// 1. Find the elements by their id
const myButton = document.getElementById("my-button");
const greeting = document.getElementById("greeting");
// 2. Listen for a click on the button
myButton.addEventListener("click", () => {
// 3. Do something: change the paragraph's text
greeting.textContent = "The spell works! 🎉";
});
新しいものを分解:
id="my-button"– 要素の名札。クラスに似てるけどidはページに1つだけ。JavaScript が要素を見つけるのに使う。const– 名前付きの箱(変数)。見つけた要素を入れる。変数は次回詳しく。document.getElementById("...")– 「ページ、この id の要素を見つけて。」addEventListener("click", () => { ... })– 「クリックしたら、波括弧の中を実行。」変な矢印() => {}は 関数——後で動くコードの包み。textContent– 要素の中のテキスト。新しいテキストを代入すると、ページ上ですぐ変わる。
やってみよう 💪
サイトに最初の呪文を追加。プロジェクトから1つ選ぶ(または自分で考える):
🏫 学校サイト——「今日の給食は?」ボタン
HTML(ホームページ):
<button id="lunch-button">What's for lunch today?</button>
<p id="lunch"></p>
script.js:
const lunchButton = document.getElementById("lunch-button");
const lunch = document.getElementById("lunch");
lunchButton.addEventListener("click", () => {
lunch.textContent = "Today: pizza and salad! 🍕";
});
🙋 個人サイト——「ジョークを言って」ボタン
<button id="joke-button">Tell me a joke</button>
<p id="joke"></p>
const jokeButton = document.getElementById("joke-button");
const joke = document.getElementById("joke");
jokeButton.addEventListener("click", () => {
joke.textContent = "Why do programmers prefer dark mode? Because light attracts bugs! 😄";
});
🌍 旅行日記——「次はどこ?」ボタン
<button id="where-button">Where are we going next?</button>
<p id="where"></p>
const whereButton = document.getElementById("where-button");
const where = document.getElementById("where");
whereButton.addEventListener("click", () => {
where.textContent = "Packing our bags: we're headed to the beach in Greece! 🌊";
});
⚽ クラブサイト——「次の試合はいつ?」ボタン
<button id="match-button">When's the next match?</button>
<p id="match"></p>
const matchButton = document.getElementById("match-button");
const match = document.getElementById("match");
matchButton.addEventListener("click", () => {
match.textContent = "Saturday at 10:00, home game vs. Riverside. Come cheer us on! 📣";
});
ボーナス:CSS でボタンをきれいに:
button {
font-size: 16px;
font-weight: bold;
padding: 10px 20px;
border: none;
border-radius: 999px;
background-color: #1d4ed8;
color: white;
cursor: pointer;
}
button:hover {
background-color: #1e40af;
}
⚠️
動かない? コンソールを開く(F12)。よくあるミス:1) HTML の id が getElementById の名前と完全一致してない(大文字小文字も!)、2) <script> が <body> の最後じゃない、3) 括弧忘れ——コンソールが行番号を教える。
✅
確認: ボタンをクリックするとページにテキストが現れる。ウェブの3言語を全部つないだ:HTML(ボタン)、CSS(見た目)、JavaScript(動き)。
このレッスンのまとめ
- すべての呪文:要素を見つける → イベントを待つ → 何かする。
document.getElementById("id")で要素を見つけ、addEventListener("click", () => {...})でクリックを待つ。textContentで要素のテキストをページ再読み込みなしですぐ変更。
© 2026 Ing. Martin Polak / AlgoRhino · コンテンツ利用規約