メソッド

  • スタイル設定・取得
    • css : CSS取得
    • addClass, removeClass : クラスの設定・削除
// pタグの文字を赤字にする
$('p').css('color','red');
// pタグのcssのcolorを取得する
console.log($('p').css('color'));
// pタグにmyStyleクラスを追加する
$('p').addClass('myStyle');
  • html属性やカスタム属性を操作・取得
    • attr, data
// aタグのhref属性を取得
console.log($('a').attr('href'));
// aタグのhref属性を設定
$('a').attr('href', 'http://google.co.jp');
// aタグのカスタム属性(data-sitename)を取得
console.log($('a').data('sitename'));
  • タグの中身操作・取得
    • text, html
    • val
    • remove(要素削除), empty
// pタグの値を設定
$('p').text('just changed');
// pタグのhtml要素を設定
$('p').html('<a href="">click me !</a>');
// inputタグの値を取得
console.log($('input').val());
// pタグの全ての子要素を削除し空にする
$("p").empty();
  • 要素を追加する
    • before, after
    • insertBefore, insertAfter
    • prepend, append
    • prependTo, appendTo
// ul直下でindexが1のli要素の前に、'just added'のli要素を追加する
var li = $('<li>').text('just added');
$('ul > li:eq(1)').before(li);
// 別の書き方
li.insertBefore($('ul > li:eq(1)'));

// すべてのul要素の前にliを追加する
$('ul').prepend(li);
li.prependTo($('ul'));
  • エフェクト
    • hide, show
    • fadeOut, fadeIn
    • toggle
// idがboxの要素を隠す
$('#box').hide(800);
// idがboxの要素をフェードイン
$('#box').fadeIn(800);
// idがboxの要素をtoggle(あったら消す、なかったら出す)
$('#box').toggle(800);
// idがboxの要素をフェードアウトし、アラート出す
$('#box').fadeOut(800, function(){
  alert("done!");
});
  • イベント
    • click
    • mouseover, mouseout, mousemove
// idがboxの要素をクリックした際alertを表示する
$('#box').click(function(){
  alert('click!!!');
});
// idがboxの要素に、、、
$('#box')
  // マウスオーバーしたら背景色を緑にする
  .mouseover(function(){
    $(this).css('background','green');
  })
  // マウス離したら背景色を赤にする
  .mouseout(function(){
    $(this).css('background','red');
  })
  // マウス動かしたらマウスのx座標を表示する
  .mousemove(function(e){
    $(this).text(e.pageX);
  });
  • formで使える
    • focus, blur
    • change
// idがnameのフォーム、、、
$('name')
  // フォーカスした場合、背景色を赤にする
  .focus(function(){
    $(this).css('background','red');
  })
  // フォーカスを外した場合、背景色を白にする
  .blur(function(){
    $(this).css('background','white');
  });

// idがmembersの値が変わった場合アラートをあげる
$('#members').change(function(){
  alert('changed!!!');
});
  • 動的に作られた要素の指定
    • on
// buttonをクリックしたらvanishクラスを持つpタグを作成し、それをクリックしたら削除する
$('button').click(function(){
  var p = $('<p>').text('vanish!').addClass('vanish');
  $(this).before(p);
});
$('body').on('click', '.vanish', function(){
  $(this).remove();
});