基本的なメソッド
要素のスタイルを操作
$( 'セレクタ' ).メソッド( パラメータ );
- ドット(.)でつなぐ
- メソッド名には必ず()をつける
- 必要な場合は、パラメータを記述する
CSS()メソッド
- 要素のCSSを操作するためのメソッド
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>CSS()メソッド</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> </head> <body> <ul> <li>HTML</li> <li>CSS</li> <li id="third">jQuery</li> <li>PHP</li> </ul> <script> $(function(){ $( '#third' ).css( 'background', 'yellowgreen' ); }); </script> </body> </html>
複数の指定
$(function(){ $( '#third' ).css( 'background', 'yellowgreen' ); $( '#third' ).css( 'font-size', '30px' ); });
width()メソッド
- 要素の幅を指定するメソッド
メソッドチェーンの指定
- 複数のメソッドを、ドットでつなぐ
$(function(){ $( '#third' ).css( 'background', 'yellowgreen' ).width( 250 ); });
addClass()メソッド
- 要素にクラスを付け加える
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>addClass()メソッド</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <style> .first { background: yellowgreen; } </style> </head> <body> <ul> <li>HTML</li> <li>CSS</li> <li>jQuery</li> <li>PHP</li> </ul> <script> $(function(){ $( 'li:first-child' ).addClass( 'first' ); }); </script> </body> </html>
- classの追加を確認する
removeClassメソッド
- 要素のクラス属性を削除する
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>removeClass()メソッド</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <style> .last { background: yellowgreen; } </style> </head> <body> <ul> <li>HTML</li> <li>CSS</li> <li>jQuery</li> <li class="last">PHP</li> </ul> <script> $(function(){ $( 'li:last-child' ).removeClass( 'last' ); }); </script> </body> </html>
実行結果、class名は削除されます。(ただし、classという語句が残るので注意が必要です。)
- 削除前
- 削除後(背景色が適用されていません)