0
0

【JavaScript】querySelectorに複数の属性を指定すると、ネストした要素にアクセスできる

Posted at

はじめに

以下のようなHTML要素があったときに、どうすれば内部要素をピンポイントで取得できるのかと思っていました。

index.html
<div id="x">
    <div class="y">This is the element we are selecting</div>
</div>

解決策

querySelectorで以下のように親要素から順に指定します。
それぞれの要素の間にスペースを書くことで、ネストされた要素にアクセスすることができました。

script.js
const a1 = document.querySelector("#x .y");
console.log(a1.innerText);
コンソール
This is the element we are selecting

ちなみに、親要素を書かなくてもネストされた要素にアクセスできますが、次のように複数の要素があると、最初の要素にアクセスされます。

index.html
<div class="y">Dummy element</div>
<div id="x">
    <div class="y">This is the element we are selecting</div>
</div>
script.js
const a1 = document.querySelector("#x .y");
const a2 = document.querySelector(".y");

console.log(a1.innerText);
console.log(a2.innerText);
コンソール
This is the element we are selecting
Dummy element
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0