【CSS】【JS】【TS】 セレクタ

■ はじめに

https://dk521123.hatenablog.com/entry/2021/03/06/234935
https://dk521123.hatenablog.com/entry/2021/03/05/113518
https://dk521123.hatenablog.com/entry/2015/05/15/000926

などで、CSSセレクタやJavaScriptのdocument.querySelector/querySelectorAll
で指定するやりかたが書いてあるので、色々なセレクタの指定の仕方をメモする。
 => document.querySelector/querySelectorAll については、
  以下の関連記事を参照のこと

DOM ~ 基本編 / オブジェクト取得 ~
https://dk521123.hatenablog.com/entry/2022/11/21/000000

目次

【1】基本
 1)要素 セレクタ - タグ指定
 2)IDセレクタ
 3)クラスセレクタ
【2】応用
 1)属性セレクタ
 2)複数セレクタ
 3)子孫セレクタ
 4)子セレクタ
 5)n番目の要素の指定

【1】基本

1)要素 セレクタ - タグ指定

そのまんま。タグを記載すればいい。

サンプル

// h3タグを指定する場合
h3

2)IDセレクタ

* 頭に「#」を付けて、IDを指定すればいい

サンプル

// <div id="hello">Hello world</div>を指定する場合
#hello

// divの中のid="hello"を指定する場合
div#hello

3)クラスセレクタ

* 頭に「.」を付けて、CSSクラス名を指定すればいい

サンプル

// <div class="world">Hello world</div>を指定する場合
.world

// divの中のclass="world"を指定する場合
div.world

【2】応用

1)属性セレクタ

* 要素(タグ)の後に、 [] で囲んで指定する

構文

【タグ】[【属性名】="【属性値】"]

サンプル

// 
select[name=""] option[value=""]

2)複数セレクタ

* 半角カンマ「,」で区切る

サンプル

// h1 or h2 or h3 を指定する場合
h1, h2, h3

3)子孫セレクタ

* 半角スペース「 」で区切る

サンプル

// 以下のようばdivの子要素h1を指定する場合
// <div><h1 class="world">Hello world</h1></div>
div h1

// divの子要素h1中のclass="world"を指定する場合
div h1.world

4)子セレクタ

* 直近の要素を「>」で指定する

サンプル

// 以下のようばdiv->span->h1を指定する場合
// <div><span><h1>Hello world</h1></span></div>
div > span > h1

5)n番目の要素の指定

* 複数要素があって、n番目の要素の指定したい場合

構文

【要素】:nth-child(【自然数(1~)】)

サンプル

/*
<div>
  <ul>
    <li>List -1</li>
    <li>List -2</li>
    <li>List -3</li>
  </ul>
</div>
*/

// 1行目
div > ul >  li:nth-child(1)

// 2行目
div > ul >  li:nth-child(2)

// 3行目
div > ul >  li:nth-child(3)

http://www.htmq.com/selector/nth-child.shtml

参考文献

http://www.htmq.com/csskihon/005.shtml

関連記事

NightWatch ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2021/03/05/113518
NightWatch ~ カスタムアサーション
https://dk521123.hatenablog.com/entry/2021/03/06/234935
Selenium in JUnit ~文法基礎編~
https://dk521123.hatenablog.com/entry/2015/05/15/000926
XML API の使い分けについて
https://dk521123.hatenablog.com/entry/2015/06/06/100247
DOM ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2011/01/07/012520
DOM ~ 基本編 / オブジェクト取得 ~
https://dk521123.hatenablog.com/entry/2022/11/21/000000
DOM ~ 基本編 / オブジェクト作成 ~
https://dk521123.hatenablog.com/entry/2022/11/19/000000
DOM ~ 基本編 / オブジェクト操作 ~
https://dk521123.hatenablog.com/entry/2011/01/09/155824