JavaScript CSSセレクタを使ってHTMLを変更(DOM操作)
DOM操作
HTMLやCSSを書き換えたりする処理のこと
基本的に出力はDOM操作
HTMLの属性の読み取り
読み取り
取得した要素.属性
書き換え
取得した要素.属性 = 値;
documentメソッド
.querySelector
const lang = document.querySelector('CSSセレクタ').lang;
.querySelectorAll
- マッチする全ての要素を取得
const thumbs = document.querySelectorAll('CSSセレクタ');
HTMLのプルダウン
optionタグのselectedをJavaScriptで設定
- selectedをオンにすると選択された状態になる
- selected = true;でserectedがオン
- selectedをなくしたい場合はfalseを代入する
- checkBoxの場合はselectedではなくcheckedにする
if (lang === 'ja') { document.querySelector('option[value="index1.html"]').selected = true; } else if (lang === 'en') { document.querySelector('option[value="index2.html"]').selected = true; }
HTMLのページ切り替え
document.getElementById('formのid値').selectのname値.onchange = function(){ location.href = document.getElementById('formのid値').selectのname値.value; }