🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

idセレクタを1つの要素に複数使ってはいけない理由

ふだん何気なく書いてるこいつらですが。

<div id="wrap" class="grid_24">hogehoge</div>

どういう時にidをつけて、どういう時にclassを振るのか、いまいち意識してませんでした。
1つの要素にidって2つとか、複数指定したらあかんとは聞くけど、
なんであかんのかっていう疑問が生まれたので調べてみた。

基本的なおさらい

idはhtmlファイルの中で一意の存在

<div id="top_sec">
  <p>IDセレクタはhtmlファイル中、一回しか登場しません。</p>
</div>

<!--中略-->

<div id="top_sec">
  <p>↑のこういうのはNGということ。</p>
</div>

CLASSセレクタは何度でも書ける

<div id="top_sec">
  <p class="text">CLASSセレクタはhtmlファイル中、何度でも使える。</p>
</div>

<!--中略-->

<div id="bottom_sec">
  <p class="text">←のこういうのがOKということ。</p>
</div>

でも知りたいのはそういうことじゃなくて。

セレクタとして一回しか使ったらあかんかもやけど、1つのidに違う単語で複数指定するのは?

何回も書けることはわかったけど、複数指定して良いん?

調べたよ!

CLASSセレクタは複数指定可能

WordPressのタグとかそうなってるもんねー。

<article id="post-292" class="post-292 post type-post status-publish format-standard hentry category-1 tag-mac tag-inst">

IDセレクタは、複数指定不可

参考:css - Can an html element have multiple ids? - Stack Overflow

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.

Q.「なんであかんのか」
A.「やっぱ決まりごとやから」

あの要素といったらアレ!ってするためには、タグ側からもセレクタ側?からも一意にしとく必要があるというわけなのねー。


くぅ。

無理矢理にでもIDを複数使いたい場合

ひねくれてるけどこんなんもアリなのねw

<div id='enclosing_id_123'><span id='enclosed_id_123'>これに指定したい!</span></div>

もはや当初の疑問はどこへやら。

getElementById()

というDOMのAPIがあるけど、同じIDが複数あっても、取れるのは最初に見つけた1つだけです。
そういえば。