0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptのquerySelector()関数の使い方

0
Posted at

JavaScriptのquerySelector()関数の使い方

querySelector()関数は、HTMLドキュメントまたは特定の要素内で、指定されたCSSセレクターに一致する最初の要素を返します。
一致する要素が存在しない場合は、nullを返します。

基本例

// HTMLドキュメント内で最初のクラス名が「.item」の要素を選択
const firstItem = document.querySelector(".item");

// 特定の要素内で選択
const container = document.getElementById("container");
const nestedButton = container.querySelector("button.primary");

// 一致する要素が存在しない場合
const notExist = document.querySelector(".no-such-class"); // nullを返す

構文

// HTMLドキュメント内で
document.querySelector(selectors)

// 特定の要素内で
element.querySelector(selectors)

戻り値

  • Documentオブジェクト(ドキュメント全体)で呼び出した場合は、ドキュメント内で指定したCSSセレクターに一致する最初の要素オブジェクトを返します。
  • Elementオブジェクト(特定の要素)で呼び出した場合は、その特定の要素内で指定したCSSセレクターに一致する最初の要素オブジェクトを返します。
  • 一致する要素が存在しない場合は、nullを返します。

特定の要素内で要素を探す

<div class="container">
    <p>子孫要素です。</p>
</div>


let container = document.querySelector(".container"); // 特定の要素オブジェクトです。

let matche = container.querySelector("p"); // 特定の要素オブジェクト内で要素を探す
/* let matche = document.querySelector(".container p"); と同じ戻り値です。 */

要素のスタイルを変更する

<div id="my-element">この要素のスタイルを変更します。</div>


const element = document.querySelector("#my-element");

element.style.backgroundColor = "lightblue";
element.style.color = "darkblue";

イベントリスナーを追加する

<button id="my-button">クリックしてください</button>


const button = document.querySelector("#my-button");

button.addEventListener("click", () => {
    alert("ボタンがクリックされました!");
});

動的に内容を追加する

<ul id="my-list"></ul>


const myList = document.querySelector("#my-list");
const items = ["項目 1", "項目 2", "項目 3"];
const itemsLength = items.length;

for (let i = 0; i < itemsLength; i++) {
    let listItem = document.createElement("li");
    listItem.textContent = items[i];
    myList.appendChild(listItem);
}

一致する要素が存在しない場合はnullを返す

<!DOCTYPE html>
<html lang="ja">
    <head>
        <title>querySelector() 例</title>
    </head>
    <body>
        <div id="my-element">この要素を選択できます。</div>
        <script>
            const nonExistentElement = document.querySelector("#non-existent-element");
            
            if (nonExistentElement === null) {
              console.log("一致する要素がありません。");
            } else {
              console.log("一致する要素を見つけました。");
            }
        </script>
    </body>
</html>

参考資料

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?