ホーム > タグ > table

table

【jQuery】tableのtrを取得したいのに。

以下のようなtableを書いたときに子要素であるtrを取得したいわけで。

  <table id="table">
    <tr>
      <td>hoge1</td>
      <td>hoge2</td>
    </tr>
    <tr>
      <td>hoge3</td>
      <td>hoge4</td>
    </tr>
    <tr>
      <td>hoge5</td>
      <td>hoge6</td>
    </tr>
  </table>
  <form action="javascript:void(0);"><input id="input" type="button" name="" value="run" /></form>

単純にjQueryを使うと

$("#input").click(function(){
  console.log($("table").children());  //jQuery(tbody)
});

としちゃうんですが。
どうやら書いてもいないjQueryオブジェクトのtbodyを返すようだ。( firfox webkit ie6,7,8で確認した )

なのでこうする

$("#input").click(function(){
  console.log($("table")[0].rows);     //[tr, tr, tr]
});

でも帰ってくるものは素のDOMなのでメソッドチェーン出来ない
なのでラップする

$("#input").click(function(){
  console.log($($("table")[0].rows));  //jQuery(tr, tr, tr)
});

出来たー。tr達が帰ってきたー。お帰り!

Home > Tags > table

Search
Feeds
Ads
Link
Meta

Return to page top