取得したオブジェクトの一覧 - Javascript

取得するオブジェクトの一覧

メソッド名 取得オブジェクト 備考
getElementById Element オブジェクト
getElementsByClassName HTMLCollection オブジェクト forEach() を使いたい場合は、Array.from() で配列に変換してから使う
getElementsByName NodeList オブジェクト
getElementsByTagName HTMLCollection オブジェクト forEach() を使いたい場合は、Array.from() で配列に変換してから使う
querySelectorAll NodeList オブジェクト
querySelector Element オブジェクト

querySelector querySelectorAll とは

CSS のセレクタを指定して要素を取得できます。

メソッド名 取得オブジェクト
querySelectorAll NodeList オブジェクト
querySelector 要素オブジェクト

「 querySelectorAll 」は、指定したセレクタをすべて取得します。

「 querySelector 」は、指定されたセレクタが複数ある場合は最初にマッチしたものを取得します。

サンプル HTML

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <input type="text" name="target" id="text1" class="target_class" value="input1">
  <input type="text" name="target" id="text2" class="target_class" value="input2">
</body>
</html>

サンプル Javascript

getElementById

script.js

window.onload = function() {
  let target = document.getElementById('text1');

  console.log(target);
}
getElementsByClassName

script.js

window.onload = function() {
  let target = document.getElementsByClassName('target_class');

  console.log(target);

  let arr = Array.from(target);
  console.log(arr)
  
  arr.forEach(function(value, index, arr){
    console.log(value);
  })
}
getElementsByName

script.js

window.onload = function() {
  let target = document.getElementsByName('target');

  console.log(target);

  target.forEach(function(value, index, target){
    console.log(value);
  });
}
getElementsByTagName

script.js

window.onload = function() {
  let target = document.getElementsByTagName('input');

  console.log(target);

  Array.from(target).forEach(function(value, index, target){
    console.log(value);
  });
}
querySelectorAll

script.js

window.onload = function() {
  let target = document.querySelectorAll('input');

  console.log(target);

  target.forEach(function(value, index, target){
    console.log(value);
  });
}
querySelector

script.js

window.onload = function() {
  let target = document.querySelector('input');

  console.log(target);
}