CSSセレクタで要素を取得する
// ── querySelector: CSS セレクターで最初の1件を取得 ──────
// 見つからない場合は null が返る(必ずnullチェックを)
const app = document.querySelector('#app'); // ID
const btn = document.querySelector('.submit-btn'); // クラス
const input = document.querySelector('input[type="email"]'); // 属性
if (btn) {
btn.textContent = 'クリック'; // null でない場合のみ操作
}
// ── querySelectorAll: 全件取得(NodeList が返る)──────
const items = document.querySelectorAll('.list-item');
items.forEach(item => {
item.classList.add('active'); // 全アイテムに active クラスを追加
});
// ── 要素を新しく作って追加する ────────────────────────
const div = document.createElement('div'); // 要素を作成
div.textContent = 'Hello World'; // テキストを設定
div.classList.add('card', 'shadow'); // クラスを追加
div.setAttribute('data-id', '123'); // 属性を設定
document.body.appendChild(div); // body の末尾に追加
// ── 属性・スタイルの操作 ──────────────────────────────
const el = document.querySelector('#title') as HTMLHeadingElement;
el?.style.setProperty('color', 'red'); // スタイルを変更TypeScriptでは型パラメータを指定するとキャストなしで型安全に使える。querySelectorAllはNodeListを返すため配列メソッドを使うにはArrayに変換する。