JavaScriptのquerySelector()で最初に一致する要素を選ぶ

document.querySelector(selector)は、CSS(カスケーディングスタイルシート)セレクターに一致する文書順で最初の要素を返します。一致がなければnull、無効なセレクターならSyntaxErrorになります。

最初に一致する要素を選ぶ

.targetはクラス、#panelはIDを指定します。読み書きする前に要素の存在を確認します。nullのプロパティを読むとエラーになります。querySelector()を参照してください。

const first = document.querySelector('.target');
if (first !== null) {
  first.textContent = '最初の項目';
}

組み合わせたセレクターで範囲を絞る

#panel .targetはIDがpanelの要素の子孫に一致します。要素をすでに取得していればpanel.querySelector('.target')でも探せます。すべて必要ならquerySelectorAll()を使います。単独の結果に添字は不要です。

const firstAnywhere = document.querySelector('.target');
const firstInPanel = document.querySelector('#panel .target');

console.log(firstAnywhere?.textContent);
console.log(firstInPanel?.textContent); 

一致なし、構文エラー、特殊なIDに対処する

セレクターが正しくても、要素が作られる前ならnullになります。対象HTMLの後にコードを置くか、外部クラシックスクリプトにdeferを指定します。???は文書が準備できても無効です。

document.querySelector('.missing'); // null

try {
  document.querySelector('???');
} catch (error) {
  console.log(error.name); // 'SyntaxError'
}

2026:Q1のようなIDを使うときは、値をCSS.escape()に渡してから#を加えます。サンプルはメモリー上に区間を作り、その子要素を探します。

{
  const section = document.createElement('section');
  const item = document.createElement('p');
  const id = '2026:Q1';
  item.id = id;
  section.append(item);

  const selector = '#' + CSS.escape(id);
  console.log(section.querySelector(selector) === item); // true
}

出力はtrueです。セレクター全体をエスケープすると先頭の#まで文字として扱います。文書全体からIDだけで探すなら、document.getElementById(id)は元の値を受け取ります。CSS.escape()を参照してください。

完全なサンプルを試す

UTF-8でquery-selector-example.htmlとして保存し、開きます。.targetでパネル外、#panel .targetでパネル内の最初の要素が強調されます。.missingはnull、???はSyntaxErrorを表示します。リセットすると初期状態に戻ります。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>CSSセレクターの最初の結果</title>
  <style>.selected { background: #fff2a8; outline: 2px solid #a76b00; }</style>
</head>
<body>
<h1>最初の要素を選ぶ</h1>
<p class="target">外側の項目</p>
<section id="panel">
  <p class="target">パネルの最初の項目</p>
  <p class="target">パネルの2番目の項目</p>
</section>
<label for="selector">CSSセレクター</label>
<select id="selector">
  <option value=".target">.target</option>
  <option value="#panel .target">#panel .target</option>
  <option value=".missing">.missing</option>
  <option value="???">???</option>
</select>
<button id="find" type="button">検索</button>
<button id="reset" type="button">リセット</button>
<p id="output" aria-live="polite"></p>
<script>
const choice = document.querySelector('#selector');
const output = document.querySelector('#output');

function choose() {
  document.querySelector('.selected')?.classList.remove('selected');
  try {
    const found = document.querySelector(choice.value);
    if (found === null) {
      output.textContent = '一致する要素がありません: null';
      return;
    }
    found.classList.add('selected');
    output.textContent = `選択: ${found.textContent.trim()}`;
  } catch (error) {
    if (error.name === 'SyntaxError') {
      output.textContent = '無効なCSSセレクター: SyntaxError';
    } else {
      throw error;
    }
  }
}

document.querySelector('#find').addEventListener('click', choose);
document.querySelector('#reset').addEventListener('click', () => {
  choice.value = '.target';
  choose();
});
choose();
</script>
</body>
</html>