はじめに
- 自分用にまとめているだけなので、ご要望ありましたら追加いたします
- 誤字や使用意図が違う等の不備がありましたらお知らせください
- 初学者向けの内容がほとんどだと思います
1. JavaScriptの変数宣言:var
/ let
/ const
の違い
特性 | var |
let |
const |
---|---|---|---|
再宣言 | ✅ 可 | ❌ 不可 | ❌ 不可 |
再代入 | ✅ 可 | ✅ 可 | ❌ 不可 |
スコープ | 関数スコープ | ブロックスコープ | ブロックスコープ |
巻き上げ | ✅(初期化される) | ✅(初期化なし) | ✅(初期化なし) |
初期化必須 | ❌ 不要 | ❌ 不要 | ✅ 必須 |
推奨度 | ❌ 推奨されない | ✅ 推奨 | ✅ よく使われる |
- 基本は
const
を使い、必要なときだけlet
を使う -
var
は古い書き方で、現在はほとんど使われません(ES6以降は非推奨)
// ✅ 推奨される書き方
const name = "Taro"; // 変更しない値
let count = 0; // 状態が変化する値(例:カウンター)
// ❌ 非推奨
var message = "Hello"; // スコープが曖昧になりがち
2. スコープ
// グローバルスコープ
const PIE = 3.14;
function foo() {
console.log(PIE); // 3.14
// 関数スコープ
const age = 20;
console.log(age); // 20
}
// ブロックスコープ
if(true) {
const name = 'Test';
console.log(name); // Test
}
console.log(PIE); // ✅ 3.14(グローバルスコープなのでアクセス可能)
console.log(age); // ❌ ReferenceError: age is not defined(関数の外からは見えない)
console.log(name); // ❌ ReferenceError: name is not defined(if ブロックの外からは見えない)
3. 基本
<script src="fileName.js"></script> // JSファイルの読込
function adNumber(a, b) { // 関数
return a + b;
}
/* Comments // コメントアウト(複数行)
multiple line */
// one line // コメントアウト(1行)
console.log(a); // コンソールに出力
document.write(a); // HTMLに直接出力
alert(a); // モーダルでメッセージ表示
confirm("送信しますか?"); // OK/キャンセルを選択
prompt("Your Name?", "A"); // ユーザーから文字列を取得
4. 変数の型
const age = 20; // number
const name = "Name" // String
const name = {first:"Name", lase:"Dayo"}; // Object
const flg = false; // boolean
const list = {"HTML", "CSS", "JS"}; // array
const a; typeof a; // undefined
const a = null; // value null
5. 文字列操作
const str = "abc,cdEcd";
const len = str.length; // 結果:9 // 文字列の長さ
str.indexOf("cd"); // 結果:5 // 引数の文字が出現する最初のインデックス(補足:見つからない場合は -1 を返す)
str.lastIndexOf("cd"); // 結果:7 // 引数の文字が出現する最後のインデックス
str.slice(2, 4); // 結果: "c," // 文字列の指定のインデックス間のみを抽出
str.replace("abc", "123"); // 結果:"123,cdEcd" // 文字列の置換(第一引数の文字を第二引数の文字に置換)
str.toUpperCase(); // 結果:"ABC,CDECD" // 全ての文字を大文字に
str.toLowerCase(); // 結果:"abc,cdecd" // 全ての文字を小文字に
str.concat(" ", "123"); // 結果:"abc,cdecd 123" // 文字列結合(補足:str に " " と "123" を順に連結した文字列を返す)
str.charAt(2); // 結果:"c" // x番目の文字を取得(インデックス換算)
str.split(","); // 結果:["abc", "cdecd"] // 文字列の分割
(100).toString(); // 結果:"100" // 数値を文字列に置換
6. オブジェクト操作
const person = {
name : 'Test',
age : 20,
gender : 'man',
};
const jobObject = {
job : 'Engineer',
salary : 1000,
}
Object.keys(person); // 結果:['name', 'age', 'gender'] // 各プロパティ名(キー)を配列で取得
Object.values(person); // 結果:['Test', 20, 'man'] // 各プロパティの値を配列で取得
Object.entries(person); // 結果:[['name', 'Test'], ['age', 20], ['gender', 'man']] // [キー, 値] のペアを要素とする配列を取得
Object.assign(person, jobObject);
// 結果:{name : 'Test', age : 20, gender : 'man', job : 'Engineer', salary : 10000} // オブジェクトを結合(マージ)
7. イベント
<input type="text" onclick="" > // クリック時
<input type="text" ondblclick="" > // ダブルクリック時
<input type="text" onmousedown="" > // マウスボタンが押された時
<input type="text" onblur="" > // フォーカスアウト時
<input type="text" onfocus="" > // フォーカスイン時
<input type="text" onmouseover="" > // カーソルが当たった時(ホバー)
<input type="text" onmouseout="" > // カーソルが離れた時
<input type="text" onchange="" > // 値が変わった後にフォーカスが外れた時
<input type="text" onkeydown="" > // キーが押された瞬間(押しっぱなし含む)
<input type="text" onkeyup="" > // キーが離された時
<form onsubmit="" ></form> // フォームの送信時(submitボタンなど)
<form onreset="" ></form> // フォームのリセット時(resetボタンなど)
<input type="text" onselect="" > // テキスト選択時(ユーザーが範囲選択した時)
8. DOM操作
// ✅ 1. 要素の取得
document.getElementById('Id') // 指定したIDを持つ要素を取得(最も基本)
document.querySelector('selector') // CSSセレクタで指定した最初の要素を取得(例: '#id', '.class')
document.querySelectorAll('selector') // CSSセレクタで一致するすべての要素を取得(NodeList)
// ✅ 2. 要素の中身・表示を操作
element.innerHTML // 要素のHTMLを取得または書き換える(HTMLタグも有効)
element.textContent // 要素のテキストのみを取得または書き換える(タグは無視)
// ✅ 3. クラス・スタイル操作
element.style.property // 要素のスタイルを直接変更(例: element.style.color = 'red')
element.classList.add('class') // 指定したクラスを追加
element.classList.remove('class') // 指定したクラスを削除
element.classList.toggle('class') // クラスのON/OFF切り替え
// ✅ 4. 属性の操作
element.setAttribute('attr', 'value') // 属性を設定(例: href, src, classなど)
element.getAttribute('attr') // 指定した属性の値を取得
element.removeAttribute('attr') // 指定した属性を削除
// ✅ 5. 子要素・DOM構造の操作
element.appendChild(child) // 子要素を末尾に追加
element.removeChild(child) // 子要素を削除
document.createElement('tag') // 新しい要素を作成(例: div, span)
parent.insertBefore(newElement, refElement) // 指定の要素の前に新要素を挿入
// ✅ 6. 親子・兄弟関係の取得
element.parentElement // 親要素を取得
element.children // 子要素(HTMLCollection)を取得
element.nextElementSibling // 次の兄弟要素を取得(要素ノード)
element.previousElementSibling // 前の兄弟要素を取得(要素ノード)
// ✅ 7. イベント操作
element.addEventListener('event', function) // イベントリスナーを登録(例: 'click')
window.onload = function() { ... } // ページ読み込み完了時に実行する関数を登録
// ✅ 8. その他
window.alert('message') // アラートポップアップを表示
console.log('message') // コンソールにログ出力(デバッグ用)
location.href // 現在のURLを取得・変更(遷移・リダイレクト用)
9. プロパティ
const inputText = document.getElementById('inputText'); // <input type="text">
const checkbox = document.getElementById('checkbox'); // <input type="checkbox">
const selectBox = document.getElementById('selectBox'); // <select>
const textarea = document.getElementById('textarea'); // <textarea>
const inputFile = document.getElementById('inputFile'); // <input type="file">
const formElement = document.getElementById('formElement'); // <form>
// value: 入力値を取得・設定(text, textarea, selectなど)
console.log(inputText.value); // 現在の入力値を取得
inputText.value = "新しい値"; // 入力値を変更
// checked: チェックボックスやラジオボタンの選択状態を取得・設定(true/false)
console.log(checkbox.checked); // チェックされているか確認
checkbox.checked = true; // チェックをつける
// selectedIndex: <select>で選択されているインデックス番号を取得・設定
console.log(selectBox.selectedIndex); // 選択中のオプションのインデックス番号を取得
selectBox.selectedIndex = 2; // 3番目のオプションを選択(0始まり)
// disabled: 要素が無効(操作不可)かどうかの取得・設定(true/false)
console.log(inputText.disabled); // 無効かどうか
inputText.disabled = true; // 無効にする(入力不可にする)
// readonly: 読み取り専用かどうかの取得・設定(true/false)
// readonlyはinput, textareaで有効
console.log(textarea.readOnly); // 読み取り専用かどうか
textarea.readOnly = true; // 読み取り専用にする
// name: 要素のname属性の値を取得
console.log(inputText.name);
// type: input要素の種類(text, checkbox, radioなど)を取得
console.log(inputText.type);
// files: ファイル選択<input type="file">で選択されたファイルのリストを取得
console.log(inputFile.files); // FileListオブジェクト(選択されたファイル群)
// length: <select>要素のオプション数を取得(select.options.lengthでも同じ)
console.log(selectBox.options.length);
// options: <select>の全ての<option>要素を取得(HTMLCollection)
console.log(selectBox.options);
// form: 要素が属している<form>要素を取得
console.log(inputText.form); // 例えば inputTextがフォーム内なら、その<form>要素を返す
// validity: フォームのバリデーション状態を確認(HTML5)
console.log(inputText.validity.valid); // trueなら入力が有効
// defaultValue: 初期のvalue属性の値
console.log(inputText.defaultValue);
// placeholder: プレースホルダー(薄いグレーで表示されるヒントテキスト)
console.log(inputText.placeholder);
10.JQuery
// jQueryの読み込み(必須)
// <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
// 🔸1.要素の取得・操作
// 要素取得(複数取得可)
$('#id') // id指定
$('.class') // class指定
$('tag') // タグ名指定
// テキスト操作
$('#id').text() // テキスト取得
$('#id').text('新しいテキスト') // テキスト設定
// HTML操作
$('#id').html() // HTML取得
$('#id').html('<b>太字</b>') // HTML設定
// フォームの値操作
$('#input').val() // 値取得
$('#input').val('abc') // 値設定
// チェックボックスの状態操作
$('#checkbox').prop('checked'); // 状態取得
// チェックボックスの状態設定
$('#checkbox').prop('checked', true); // チェックを入れる
$('#checkbox').prop('checked', false); // チェックを外す
// 属性操作
$('#id').attr('src') // 属性取得
$('#id').attr('src', 'img.jpg') // 属性設定
// クラス操作
$('#id').addClass('highlight') // クラス追加
$('#id').removeClass('highlight')// クラス削除
$('#box').toggleClass('active') // クラスのON/OFF切り替え
// 🔸2.イベントの処理
// 単一イベント登録(クリック)
$('#btn').click(function() {
// 処理内容
});
// 複数イベント対応(クリック・マウスオーバー)
$('#btn').on('click mouseover', function() {
// 処理内容
});
// イベント解除
$('#btn').off('click');
// キーボードイベント
$('#input').keydown(function(e) {
// e.keyCodeなどでキー判定可
});
// 🔸3.DOMの追加・削除・置換
// 要素の追加
$('#parent').append('<div>末尾に追加</div>'); // 子要素の末尾に追加
$('#parent').prepend('<div>先頭に追加</div>'); // 子要素の先頭に追加
// 要素の削除
$('#element').remove();
// 要素の置換
$('#old').replaceWith('<div>置換後の要素</div>');
// 🔸4.表示・非表示・アニメーション
$('#id').hide(); // 非表示
$('#id').show(); // 表示
$('#id').fadeIn(); // フェードイン表示
$('#id').fadeOut(); // フェードアウト非表示
$('#id').slideUp(); // スライドアップで非表示
$('#id').slideDown(); // スライドダウンで表示
// 🔸5.その他便利メソッド
// 複数要素に対して繰り返し処理
$('.items').each(function(index, element) {
// this または element で現在の要素にアクセス
});
// CSS動的変更
$('#id').css('color', 'red');
// データの紐付け
$('#id').data('key', 'value');
// 要素の複製
$('#id').clone();
11.Ajax
// GETリクエスト
$.ajax({
url: '/api/data',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function() {
alert('通信失敗');
}
});
// 上記を簡潔に書くと以下のようになる
$.get('/api/data', function(data) {
console.log(data);
});
サンプルコード
- JavaScript(DOM操作)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>DOM操作サンプル</title>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
.box {
width: 100px;
height: 100px;
background-color: skyblue;
margin: 10px;
display: inline-block;
}
</style>
</head>
<body>
<h2>名前を入力してください</h2>
<input type="text" id="nameInput" placeholder="名前を入力">
<button id="changeBtn">表示</button>
<p id="outputText"></p>
<h2>ボックスを追加</h2>
<button id="addBoxBtn">追加</button>
<div id="boxArea"></div>
<script>
// 名前表示ボタンの処理
const changeBtn = document.getElementById('changeBtn');
changeBtn.addEventListener('click', () => {
const name = document.getElementById('nameInput').value;
const output = document.getElementById('outputText');
output.textContent = `${name} さん、こんにちは!`;
output.classList.toggle('highlight'); // ハイライト切り替え
});
// ボックス追加ボタンの処理
const addBoxBtn = document.getElementById('addBoxBtn');
const boxArea = document.getElementById('boxArea');
addBoxBtn.addEventListener('click', () => {
const newBox = document.createElement('div');
newBox.classList.add('box');
newBox.textContent = 'Box';
newBox.addEventListener('click', () => {
alert('ボックスがクリックされました!');
});
boxArea.appendChild(newBox);
});
</script>
</body>
</html>
- JQuery
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>jQuery 基本操作サンプル</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.highlight { background-color: yellow; }
.active { color: red; }
#box { padding: 10px; border: 1px solid #333; margin-top: 10px; }
</style>
</head>
<body>
<h2>1. 要素の取得と操作</h2>
<div id="textDiv">元のテキスト</div>
<input type="text" id="input" value="初期値" />
<img id="img" src="https://via.placeholder.com/100" alt="サンプル画像" />
<button id="btnTextChange">テキスト変更</button>
<button id="btnHtmlChange">HTML変更</button>
<button id="btnAddClass">クラス追加</button>
<button id="btnRemoveClass">クラス削除</button>
<h2>2. イベントの処理</h2>
<button id="btn">クリックしてね</button>
<h2>3. DOMの追加・削除・操作</h2>
<div id="parent" style="border:1px solid #ccc; padding: 10px;">
<div id="old">古い要素</div>
</div>
<button id="btnAppend">末尾に追加</button>
<button id="btnPrepend">先頭に追加</button>
<button id="btnRemove">要素削除</button>
<button id="btnReplace">置換</button>
<button id="btnToggleClass">クラス切替</button>
<div id="box">このボックスのクラスを切り替えます</div>
<h2>4. チェックボックスの操作</h2>
<label><input type="checkbox" id="checkbox" /> チェックボックス</label><br />
<button id="btnCheckState">チェック状態を表示</button>
<button id="btnCheckOn">チェックを入れる</button>
<button id="btnCheckOff">チェックを外す</button>
<script>
$(function() {
// 1. 要素操作
$('#btnTextChange').click(function() {
$('#textDiv').text('テキストが変更されました!');
});
$('#btnHtmlChange').click(function() {
$('#textDiv').html('<b>太字に変更されました!</b>');
});
$('#btnAddClass').click(function() {
$('#textDiv').addClass('highlight');
});
$('#btnRemoveClass').click(function() {
$('#textDiv').removeClass('highlight');
});
// 2. イベント処理
$('#btn').on('click mouseover', function(e) {
if (e.type === 'click') {
alert('クリックされました');
} else if (e.type === 'mouseover') {
console.log('マウスオーバー');
}
});
// 3. DOM操作
$('#btnAppend').click(function() {
$('#parent').append('<div>末尾に追加された要素</div>');
});
$('#btnPrepend').click(function() {
$('#parent').prepend('<div>先頭に追加された要素</div>');
});
$('#btnRemove').click(function() {
$('#old').remove();
});
$('#btnReplace').click(function() {
$('#parent > div:first').replaceWith('<div>置換後の要素</div>');
});
$('#btnToggleClass').click(function() {
$('#box').toggleClass('active');
});
// 4. チェックボックス操作
$('#btnCheckState').click(function() {
alert('チェック状態: ' + $('#checkbox').prop('checked'));
});
$('#btnCheckOn').click(function() {
$('#checkbox').prop('checked', true);
});
$('#btnCheckOff').click(function() {
$('#checkbox').prop('checked', false);
});
});
</script>
</body>
</html>