【JavaScript】もう迷わない!要素取得は querySelector 系を使えばOKな理由

JavaScriptで画面に動きをつける時、一番最初にやるのが「HTMLの要素を取得する」ことです。 昔からの書き方と現代の書き方があり、「結局どれを使えばいいの?」と迷う方も多いのではないでしょうか。

結論から言うと、querySelector と querySelectorAll の2つをマスターしておけばほぼ間違いありません! 今回は、古くからある getElementById などとの違いや、なぜ現代では querySelector 系が主流なのかを、動きがわかるデモと一緒に解説します。

デモ動作

See the Pen JavaScriptで要素を取得するメソッドまとめ by mikanbako (@mikanbako) on CodePen.

全画面でのデモ動作は以下のリンクからご確認下さい!(別タブで開かれます)

実装コード紹介

【HTML】

<div class="l-wrap">
  <h2>要素取得メソッド 比較デモ</h2>
  
  <div class="p-demo-box">
    <!-- ID指定の要素 -->
    <h3 id="js-title" class="c-title">ここはID指定(#js-title)です</h3>
    
    <!-- クラス指定の要素(複数) -->
    <p class="c-text js-text">ここはクラス指定(.js-text)の1つ目です</p>
    <p class="c-text js-text">ここはクラス指定(.js-text)の2つ目です</p>
    <p class="c-text js-text">ここはクラス指定(.js-text)の3つ目です</p>

    <!-- トリガーとなるボタン -->
    <div class="p-btn-group">
      <button id="js-btn-id" class="c-btn">getElementById で色を変える</button>
      <button id="js-btn-class" class="c-btn">getElementsByClassName で文字サイズを変える</button>
      <button class="c-btn c-btn--query js-btn-query">querySelector で色を変える</button>
      <button class="c-btn c-btn--query js-btn-query-all">querySelectorAll で太字にする</button>
      <button class="c-btn c-btn--reset js-btn-reset">リセット</button>
    </div>
  </div>
</div>

【CSS】

/* ベース装飾 */
.l-wrap {
  padding: 40px 20px;
  max-width: 600px;
  margin: 0 auto;
  color: #3e3e3e;
  line-height: 1.6;
}

h2 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #1bb4d4;
  text-align: center;
}

.p-demo-box {
  padding: 40px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgb(0 0 0 / 5%);
}

/* 見出しとテキストの装飾 */
.c-title {
  padding-bottom: 10px;
  margin-bottom: 20px;
  font-size: 18px;
  border-bottom: 2px solid #eee;
  transition: background-color 0.3s;
}

.c-text {
  margin-bottom: 15px;
  font-size: 16px;
  transition:
    color 0.3s,
    font-weight 0.3s,
    font-size 0.3s;
}

/* ボタンの装飾 */
.p-btn-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 30px;
}

.c-btn {
  padding: 12px 20px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  cursor: pointer;
  background: #1bb4d4;
  border-radius: 6px;
  transition: opacity 0.2s;
}

.c-btn--query {
  background: #e83e8c;
}

.c-btn--reset {
  background: #333;
}

.c-btn:hover {
  opacity: 0.8;
}

【JavaScript】

/* =========================================
   💡 1. 古くからある取得方法
========================================= */
const btnId = document.getElementById('js-btn-id');
const btnClass = document.getElementById('js-btn-class');

btnId.addEventListener('click', () => {
  // getElementById は「ID名」をそのまま文字列で渡す(#は不要)
  const title = document.getElementById('js-title');
  title.style.backgroundColor = '#ffff66'; // 背景を黄色に!
});

btnClass.addEventListener('click', () => {
  // getElementsByClassName は「クラス名」をそのまま文字列で渡す(.は不要)
  const allTexts = document.getElementsByClassName('js-text');
  // Array.from()で変換してから forEach を使用する
  Array.from(allTexts).forEach((text) => {
    text.style.fontSize = '20px'; // すべて'20px'にする!
  });
});

/* =========================================
   💡 2. 現代の主流な取得方法(CSSセレクタ)
========================================= */
const btnQuery = document.querySelector('.js-btn-query');
const btnQueryAll = document.querySelector('.js-btn-query-all');

btnQuery.addEventListener('click', () => {
  // querySelector は条件に合う「最初の一つ」だけ取得する
  const firstText = document.querySelector('.js-text');
  firstText.style.color = '#e83e8c'; // 1つ目だけピンク文字に!
});

btnQueryAll.addEventListener('click', () => {
  // querySelectorAll は条件に合う「すべて」を取得する
  const allTexts = document.querySelectorAll('.js-text');
  // forEachを使って一つずつ処理する(そのまま forEach が使える!)
  allTexts.forEach((text) => {
    text.style.fontWeight = 'bold'; // すべて太字に!
  });
});

/* =========================================
   リセット処理
========================================= */
const btnReset = document.querySelector('.js-btn-reset');

btnReset.addEventListener('click', () => {
  const title = document.getElementById('js-title');
  title.style.backgroundColor = '#ffffff';

  const firstText = document.querySelector('.js-text');
  firstText.style.color = '#3e3e3e';

  const allTexts = document.querySelectorAll('.js-text');
  allTexts.forEach((text) => {
    text.style.fontWeight = 'normal';
    text.style.fontSize = '16px';
  });
});

コードの解説・querySelector のおすすめ理由

CSSと同じ書き方で直感的!

// クラス名で取得
const elementClass = document.querySelector('.js-text');

// ID名で取得
const elementId = document.querySelector('#js-text');

// data属性で取得
const elementData = document.querySelector('[data-role="admin"]');

.js-text や #js-title 、さらには [data-role="admin"] のような属性まで、CSSセレクタをそのまま文字列として渡せるので、条件の指定が非常に柔軟でわかりやすいです。

配列操作(forEach)がカンタン!

従来の getElementsByClassName で複数の要素を取得すると「HTMLCollection」という少し扱いづらいデータになり、そのままでは forEach が使えません(配列に変換する手間がいります)。

// getElementsByClassName は「クラス名」をそのまま文字列で渡す(.は不要)
const allTexts = document.getElementsByClassName('js-text');
// Array.from()で変換してから forEach を使用する
Array.from(allTexts).forEach((text) => {
  text.style.fontSize = '20px'; // すべて'20px'にする!
});

一方、querySelectorAll は「NodeList」を返すため、そのまま forEach でループ処理ができるのが、重宝される理由です!

// querySelectorAll は条件に合う「すべて」を取得する
const allTexts = document.querySelectorAll('.js-text');
// forEachを使って一つずつ処理する(そのまま forEach が使える!)
allTexts.forEach((text) => {
  text.style.fontWeight = 'bold'; // すべて太字に!
});

補足:公式ドキュメント

・MDN: getElementById()
・MDN: getElementsByClassName()
・MDN: querySelector()
・MDN: querySelectorAll()

まとめ

今回はJavaScriptでの「要素の取得メソッド」について、昔からある書き方と現代の主流な書き方を比較してみました。

現場の古いコードを保守する際などは getElementById や getElementsByClassName を見かけることもありますが、これから新しくコードを書くなら、迷わず querySelector と querySelectorAll を使いましょう!

CSSと同じセレクタの書き方で直感的に指定でき、さらに複数の要素を取得した際のループ処理(forEach)もそのまま使えるため、コードがスッキリと読みやすくなります。 DOM操作の第一歩となる非常に重要な部分なので、ぜひこの使い分けをマスターして、フロントエンド開発に活かしていきましょう!

Prev
Next