ざっくりとDOM要素の取得関数一覧。
querySelectorとquerySelectorAllでほぼ大丈夫だけど ページ数が多かったりするときはgetElementBy... の方が処理が早いのでいいらしい。
詳細の要素を指定したい場合などはページ数が多くても併用する。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <h1>h1タイトル</h1> <p id="pId" class="Attr">段落<span>スパン</span></p> <p class="Attr">段落2<span>スパン2</span></p> <p class="Attr">段落3</p> <input type="text" name="nameAttr"> <input type="password" name="pwdAttr"> <script> const pid = document.getElementById("pId"); console.log(pid); const getClassAttr = document.getElementsByClassName("Attr"); console.log(getClassAttr) const getPAll = document.getElementsByTagName("p") console.log(getPAll) const getNameTypeText = document.getElementsByName("text"); const getParentSpan = document.querySelector("span"); const getParentSpan2 = getParentSpan.closest("p") const getH1broTypePass = document.querySelector('h1 ~ [name = "pwdAttr"]'); const getChildpId = document.querySelector('#pId > *') const getNextText = document.querySelector('input + [name="text"]'); console.log(getNameTypeText) console.log(getParentSpan2) console.log(getH1broTypePass) console.log(getChildpId) console.log(getNextText) </script> </body> </html>
取得したHTMLを表示・編集などする
console.log(getPAll[1].innerHTML) console.log(getPAll[0].textContent)