セレクタ
JQのセレクタはHTMLの一部分だけ抜き出しスタイルを適用できる。
HTMLの要素を取ってくると考えるといい。
その一部分や要素を的確に指定するときにセレクタを用いる。
○IDセレクタ
・ピンポイントでページ内の要素が欲しいときに最適なセレクタ
・HTMLでidで指定した部分を取ってくる。
・CSSと同様[#]を使う。
HTML
<style> #div1{ width:100px; height:100px; background:#FFCC00; } </style> </head> <body> <div id="div1"></div> <script> $('#div1').click(function(){ alert ('クリックされました'); }); </script> </body>
○classセレクタ
・2つ以上の要素に何かしたいときに最適なセレクタ
・HTMLでclassで指定した部分をとってくる
・CSSと同様に[.(ドット)]を使って指定する
HTML
<body> <ul> <li class="man">Paul</li> <li class="man">Billy</li> <li class="woman">Alice</li> <li class="man">Taro</li> <li class="woman">Hanako</li> </ul> <script> $(function(){ $('.man').css('background','lightblue'); $('.woman').css('background','pink'); }); </script> </body>
○タイプセレクタ(element)
・指定した要素名の要素すべてをとってくる
・body要素も指定できる
HTML
<body> <h1>Heading</h1> <p>The quick brown fox jumps over the lazy dog.</p> <ul> <li>The quick brown fox jumps over the lazy dog.</li> <li>The quick brown fox jumps over the lazy dog.</li> </ul> <script> $(function(){ $('p').css('background','pink'); $('li').css('background','yellowgreen'); }); $(function(){ $('body').css('background','lightblue') }); </script> </body>
○子孫セレクタ
・CSSと同様半角スペースで子 孫で指定する
HTML
<body> <div> <p>I have a <strong>pen</strong>.</p> </div> <ul> <li>His <strong>pen</strong> is red.</li> <li>I need his <strong>pen</strong> .</li> </ul> <p>She doesn't need a <strong>pen</strong>.</p> <script> $(function(){ $('div strong').css('background','lightblue'); $('ul strong').css('background','pink'); }); </script> </body>
・要素名の代わりにアスタリスク( * )を指定すると、文書内の全ての要素にそのスタイルが適用される
・
HTML
<body> <h1>Heading</h1> <p>The quick brown fox jumps over the lazy dog.</p> <ul> <li><span>The quick brown fox jumps over the lazy dog.</span></li> <li>The quick brown fox jumps over the lazy dog.</li> <li><span>The quick brown fox jumps over the lazy dog.</span></li> <li>The quick brown fox jumps over the lazy dog.</li> </ul> <script> $(function(){ $('li *').css('background','yellowgreen');}); </script> </body>
グループセレクタ
・基本はタイプセレクタと同じ指定方法
・要素を[,(カンマ)]で区切ることで一度に複数の要素を指定できる。
HTML
<body> <h1>Heading</h1> <p>The quick brown fox jumps over the lazy dog.</p> <ul> <li class="first">The quick brown fox jumps over the lazy dog.</li> <li class="second">The quick brown fox jumps over the lazy dog.</li> <li class="third">The quick brown fox jumps over the lazy dog.</li> <li class="fouth">The quick brown fox jumps over the lazy dog.</li> </ul> <script> $(function(){ $( '.first, .third' ).css( 'background', 'yellowgreen' ); });</script> </body>