JavaScriptとHTML
この記事ではJavaScriptとHTMLについて説明します。
YouTube Video
javascript-html-dom.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>JavaScript & HTML</title>
6 <style>
7 * {
8 box-sizing: border-box;
9 }
10
11 body {
12 margin: 0;
13 padding: 2em;
14 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
15 background-color: #f7f9fc;
16 color: #333;
17 line-height: 1.6;
18 }
19
20 .container {
21 max-width: 800px;
22 margin: 0 auto;
23 padding: 1em;
24 background-color: #ffffff;
25 border: 1px solid #ccc;
26 border-radius: 10px;
27 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
28 }
29
30 h1, h2 {
31 font-size: 1.5rem;
32 color: #007bff;
33 margin-top: 0.5em;
34 margin-bottom: 0.5em;
35 border-left: 5px solid #007bff;
36 padding-left: 0.6em;
37 background-color: #e9f2ff;
38 }
39
40 button {
41 display: block;
42 margin: 1em auto;
43 padding: 0.75em 1.5em;
44 font-size: 1rem;
45 background-color: #007bff;
46 color: white;
47 border: none;
48 border-radius: 6px;
49 cursor: pointer;
50 transition: background-color 0.3s ease;
51 }
52
53 button:hover {
54 background-color: #0056b3;
55 }
56
57 #output {
58 margin-top: 1em;
59 background-color: #1e1e1e;
60 color: #0f0;
61 padding: 1em;
62 border-radius: 8px;
63 min-height: 200px;
64 font-family: Consolas, monospace;
65 font-size: 0.95rem;
66 overflow-y: auto;
67 white-space: pre-wrap;
68 }
69
70 .highlight {
71 outline: 3px solid #ffc107; /* yellow border */
72 background-color: #fff8e1; /* soft yellow background */
73 transition: background-color 0.3s ease, outline 0.3s ease;
74 }
75
76 .active {
77 background-color: #28a745; /* green background */
78 color: #fff;
79 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
80 transition: background-color 0.3s ease, box-shadow 0.3s ease;
81 }
82 </style>
83</head>
84<body>
85 <div class="container">
86 <h1>JavaScript Console</h1>
87 <button id="executeBtn">Execute</button>
88 <div id="output"></div>
89 </div>
90
91 <div class="container">
92 <h2>HTML Sample</h2>
93 <div id="content">Hello, World!</div>
94 <button id="changeText">Change Text</button>
95 </div>
96
97 <script>
98 // Override console.log to display messages in the #output element
99 (function () {
100 const originalLog = console.log;
101 console.log = function (...args) {
102 originalLog.apply(console, args);
103 const output = document.getElementById('output');
104 output.textContent += args.map(String).join(' ') + '\n';
105 };
106 })();
107
108 document.getElementById('executeBtn').addEventListener('click', () => {
109 // Prevent multiple loads
110 if (document.getElementById('externalScript')) return;
111
112 const script = document.createElement('script');
113 script.src = 'javascript-html-dom.js';
114 script.id = 'externalScript';
115 //script.onload = () => console.log('javascript-html-dom.js loaded and executed.');
116 //script.onerror = () => console.log('Failed to load javascript-html-dom.js.');
117 document.body.appendChild(script);
118 });
119 </script>
120</body>
121</html>
JavaScriptにおけるwindow
オブジェクト
JavaScriptのwindow
オブジェクトは、ブラウザ環境におけるグローバルオブジェクトであり、ウェブページやブラウザウィンドウに関連する機能や情報を提供します。window
はブラウザのグローバルスコープであるため、ブラウザで動作するJavaScriptコードは全てwindow
オブジェクトの一部となります。window
オブジェクトはブラウザ環境でJavaScriptを動作させる上で重要な役割を果たし、多くのAPIやプロパティが提供されています。
window
オブジェクトの主な機能
プロパティ
1// Get and display the document's title
2console.log(`Title: ${window.document.title}`);
3
4// Get and display the current URL
5console.log(`URL: ${window.location.href}`);
6
7// Go back to the previous page
8// Note: this will navigate back in history, so be careful when running it
9console.log("Navigating back to the previous page...");
10window.history.back();
11
12// Display the browser's user agent
13console.log(`User Agent: ${window.navigator.userAgent}`);
14
15// Display the width and height of the viewport
16console.log(`Viewport Width: ${window.innerWidth}`);
17console.log(`Viewport Height: ${window.innerHeight}`);
window.document
: 現在のHTMLドキュメントにアクセスします。window.location
: 現在のURLやブラウザのナビゲーションを管理します。window.history
: ブラウザの履歴情報にアクセスし、進む、戻るといった操作を行います。window.navigator
: ブラウザやデバイスに関する情報を提供します。window.innerWidth
/window.innerHeight
: ビューポートの幅や高さを取得します。
メソッド
1// Show an alert
2window.alert('Hello, this is an alert!');
3
4// Show a confirmation dialog
5if (window.confirm('Are you sure you want to proceed?')) {
6 console.log('User clicked OK');
7} else {
8 console.log('User clicked Cancel');
9}
10
11// Show a prompt dialog
12const userInput = window.prompt('Please enter your name:');
13console.log(`Hello, ${userInput}!`);
14
15// Open a new tab
16window.open('https://www.example.com', '_blank');
17
18// Display a message after 3 seconds
19window.setTimeout(() => {
20 console.log('This message appears after 3 seconds!');
21}, 3000);
22
23// Display a message every second
24const intervalId = window.setInterval(() => {
25 console.log('This message appears every second!');
26}, 1000);
27
28// Clear the interval after 5 seconds
29setTimeout(() => {
30 clearInterval(intervalId);
31 console.log('Interval cleared.');
32}, 5000);
window.alert()
: アラートダイアログを表示します。window.confirm()
: ユーザーに確認を求めるダイアログを表示し、OKまたはキャンセルの結果を返します。window.prompt()
: ユーザーに入力を求めるダイアログを表示し、入力値を取得します。window.open()
: 新しいウィンドウやタブを開きます。window.setTimeout()
/window.setInterval()
: タイマーを設定し、一定時間後または一定間隔で関数を実行します。
イベントハンドリング
1// Display a message when the page is fully loaded
2window.onload = () => {
3 console.log('Page is fully loaded!');
4};
5
6// Display a message when the window is resized
7window.onresize = () => {
8 console.log('Window resized! New size:', window.innerWidth, 'x', window.innerHeight);
9};
10
11// Display a message when the page is being scrolled
12window.onscroll = () => {
13 console.log('Page is being scrolled!');
14};
window.onload
: ページが完全に読み込まれた際に実行されるイベントです。window.onresize
: ウィンドウのサイズが変更された際に実行されるイベントです。window.onscroll
: ユーザーがページをスクロールした際に発火するイベントです。
グローバル変数としての役割
1var myVar = 10;
2console.log(window.myVar); // 10
window
オブジェクトは、グローバル変数や関数を保持します。つまり、宣言した変数や関数は自動的にwindow
のプロパティになります。
JavaScriptにおけるDOM操作
JavaScriptのDOM(Document Object Model)操作は、ウェブページの要素を動的に操作するために使用されます。DOMは、HTMLドキュメントの構造をツリーとして表現し、JavaScriptを使ってその構造を変更したり、ページの表示を制御したりすることができます。
DOMの基本
DOMは、ウェブページのHTMLをオブジェクトとして扱い、要素や属性にアクセスしたり変更したりできます。document
オブジェクトを使って、HTMLドキュメントにアクセスします。
DOM要素の取得
JavaScriptでは、DOMの要素にアクセスするためのいくつかのメソッドがあります。
document.getElementById()
:id
属性で要素を取得します。document.getElementsByClassName()
: クラス名で要素を取得します。HTMLCollection
を返します。HTMLCollection
はライブコレクションで、DOMの変更がリアルタイムに反映されます。document.getElementsByTagName()
: タグ名で要素を取得します。HTMLCollection
を返します。document.querySelector()
: CSSセレクタを使って最初の一致する要素を取得します。document.querySelectorAll()
: CSSセレクタを使って一致する全ての要素を取得します。NodeList
を返します。NodeList
は静的コレクションで、取得時点の内容を保持し、後からのDOM変更は反映されません。
例: getElementById
とquerySelector
1<div id="content">Hello, World!</div>
2<button id="changeText">Change Text</button>
1const content = document.getElementById('content');
2console.log(content.textContent); // "Hello, World!"
3
4const button = document.querySelector('#changeText');
DOMの操作
取得した要素に対して、様々な操作を行うことができます。
テキストの変更
要素のテキストを変更するには、textContent
やinnerHTML
を使います。
textContent
: 要素のテキスト内容を取得または変更します。HTMLタグは解釈されません。innerHTML
: 要素のHTML内容を取得または変更します。HTMLタグを含む文字列も処理されます。
1content.textContent = 'Hello, world!'; // Change the text
2button.innerHTML = '<strong>Click to change</strong>'; // Change including HTML
属性の変更
要素の属性を変更するには、setAttribute()
やgetAttribute()
を使用します。
1button.setAttribute('disabled', 'true'); // Disable the button
2const id = content.getAttribute('id'); // Get the "content"
3console.log(id);
CSSの変更
CSSスタイルを変更するには、style
プロパティを使います。
1content.style.color = 'red'; // Change the text color to red
2content.style.fontSize = '20px'; // Change the font size
クラスの操作
要素にクラスを追加したり削除したりするには、classList
を使います。
add()
: クラスを追加します。remove()
: クラスを削除します。toggle()
: クラスの有無に応じて追加または削除します。contains()
: クラスが存在するかを確認します。
1content.classList.add('highlight'); // Add a class
2button.classList.toggle('active'); // Toggle a class
DOM要素の作成と削除
新しい要素の作成
新しい要素を作成して、DOMに追加するには、document.createElement()
を使います。
1const newDiv = document.createElement('div'); // Create a new div element
2newDiv.textContent = 'This is a new element';
3document.body.appendChild(newDiv); // Append to the body element
要素の削除
要素を削除するには、remove()
メソッドを使います。
1newDiv.remove(); // Remove the created element
イベントの追加
DOM操作の一環として、ユーザーの操作に応じたイベントハンドラーを追加することができます。addEventListener()
を使うと、クリックやキーボード操作などのイベントに対して処理を実行できます。
1button.addEventListener('click', () => {
2 content.textContent = 'The text has been changed';
3});
この例では、ボタンをクリックしたときに、#content
要素のテキストが変更されます。
DOMツリーの移動
DOM内の要素を移動して、親要素や兄弟要素にアクセスすることも可能です。
parentNode
: 親ノードにアクセスできます。childNodes
: 子ノードにアクセスできます。HTMLのタグのような要素ノードだけでなく、テキストノードやコメントノードなども含めた、全てのタイプのノードにアクセスできます。firstChild
/lastChild
: 最初と最後の子要素にアクセスできます。nextSibling
/previousSibling
: 次の兄弟要素と前の兄弟要素にアクセスできます。
1const parent = content.parentNode; // Get the parent element
2const firstChild = parent.firstChild; // Get the first child element
3console.log(firstChild);
例:リストに新しい項目を追加
以下は、リストに新しい項目を追加する例です。
1// Get the container element where the HTML will be inserted
2const content = document.getElementById('content');
3
4// Create the <ul> element with id="list"
5const list = document.createElement('ul');
6list.id = 'list';
7
8// Add initial list items
9const item1 = document.createElement('li');
10item1.textContent = 'Item 1';
11list.appendChild(item1);
12
13const item2 = document.createElement('li');
14item2.textContent = 'Item 2';
15list.appendChild(item2);
16
17// Create the <button> element with id="addItem"
18const addItemButton = document.createElement('button');
19addItemButton.id = 'addItem';
20addItemButton.textContent = 'Add Item';
21
22// Append the list and button to the content container
23content.appendChild(list);
24content.appendChild(addItemButton);
25
26// Add event listener to the button
27addItemButton.addEventListener('click', () => {
28 const newItem = document.createElement('li');
29 newItem.textContent = 'New Item';
30 list.appendChild(newItem);
31});
このコードでは、「アイテムを追加」ボタンをクリックすると、新しい<li>
要素がリストに追加されます。
まとめ
- JavaScriptのDOM操作を使って、HTMLドキュメント内の要素を取得、変更、作成、削除することが可能です。
getElementById()
やquerySelector()
などのメソッドで要素を取得できます。textContent
やinnerHTML
でテキストやHTMLを変更し、setAttribute()
で属性を操作できます。- 新しい要素の作成は
createElement()
、削除はremove()
を使います。 - イベントハンドリングを通じて、ユーザーの操作に反応するインタラクティブなウェブページを作成できます。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。