jQueryで要素の扱い
WordPressのプラグインなど、直接HTMLを編集するのが困難な場合jQueryのDOM操作が役立ちます。
要素の移動させる
4つのポイントに要素を移動させることができます。それぞれ以下の通りです。
.insertBefore
移動させる要素を指定した要素の前に移動させます。
before
1 2 3 4 5 6 7 8 9 10 |
<div id="sample01"> <p>ターゲット要素</p> <table> <tr> <th>ダミー</th> <td>ダミー</td> </tr> </table> <span>移動させる要素</span> </div> |
.insertBeforeでspanをpの前に持ってきます。
1 2 3 4 5 |
<script> jQuery(function($){ $("#sample01 span").insertBefore("#sample01 p"); }); </script> |
after
1 2 3 4 5 6 7 8 9 10 |
<div id="sample01"> <span>移動させる要素</span> <p>ターゲット要素</p> <table> <tr> <th>ダミー</th> <td>ダミー</td> </tr> </table> </div> |
.insertAfter
移動させる要素を指定した要素の後に移動させます。
before
1 2 3 4 5 6 7 8 9 10 |
<div id="sample01"> <p>ターゲット要素</p> <table> <tr> <th>ダミー</th> <td>ダミー</td> </tr> </table> <span>移動させる要素</span> </div> |
.insertAfterでspanをpの後に持ってきます。
1 2 3 4 5 |
<script> jQuery(function($){ $("#sample01 span").insertAfter("#sample01 p"); }); </script> |
after
1 2 3 4 5 6 7 8 9 10 |
<div id="sample01"> <p>ターゲット要素</p> <span>移動させる要素</span> <table> <tr> <th>ダミー</th> <td>ダミー</td> </tr> </table> </div> |
.prependTo
移動させる要素を指定した要素の中の前に移動させます。
before
1 2 3 4 5 6 7 8 9 10 |
<div id="sample01"> <p>ターゲット要素</p> <table> <tr> <th>ダミー</th> <td>ダミー</td> </tr> </table> <span>移動させる要素</span> </div> |
.prependToでspanをpの中の前に持ってきます。
1 2 3 4 5 |
<script> jQuery(function($){ $("#sample01 span").prependTo("#sample01 p"); }); </script> |
after
1 2 3 4 5 6 7 8 9 |
<div id="sample01"> <p><span>移動させる要素</span>ターゲット要素</p> <table> <tr> <th>ダミー</th> <td>ダミー</td> </tr> </table> </div> |
.appendTo
移動させる要素を指定した要素の中の後に移動させます。
before
1 2 3 4 5 6 7 8 9 10 |
<div id="sample01"> <p>ターゲット要素</p> <table> <tr> <th>ダミー</th> <td>ダミー</td> </tr> </table> <span>移動させる要素</span> </div> |
.appendToでspanをpの中の後に持ってきます。
1 2 3 4 5 |
<script> jQuery(function($){ $("#sample01 span").appendTo("#sample01 p"); }); </script> |
after
1 2 3 4 5 6 7 8 9 |
<div id="sample01"> <p>ターゲット要素<span>移動させる要素</span></p> <table> <tr> <th>ダミー</th> <td>ダミー</td> </tr> </table> </div> |
要素を追加する
要素を追加する場合はも4つのポイントに追加できます。それぞれ要素移動のinsertとToをぬいた形です。
.before
1 2 3 4 5 6 7 8 |
<script> jQuery(function($){ $("#sample01 p").before("※"); }); </script> <div id="sample01"> ※<p>ターゲット要素</p> </div> |
.afte
1 2 3 4 5 6 7 8 |
<script> jQuery(function($){ $("#sample01 p").afte("※"); }); </script> <div id="sample01"> <p>ターゲット要素</p>※ </div> |
.prepend
1 2 3 4 5 6 7 8 |
<script> jQuery(function($){ $("#sample01 p").prepend("※"); }); </script> <div id="sample01"> <p>※ターゲット要素</p> </div> |
.append
1 2 3 4 5 6 7 8 |
<script> jQuery(function($){ $("#sample01 p").append("※"); }); </script> <div id="sample01"> <p>ターゲット要素※</p> </div> |
要素の文字列置換
要素の文字列を置換する場合は.replaceを用います。
1 2 3 4 5 6 7 8 |
<script> jQuery(function($){ $('span').each(function(){ var txt = $(this).text(); $(this).text(txt.replace("置き換わる文字列","置き換える文字列")); }); }); </script> |
before
1 |
<span>置き換わる文字列</span> |
after
1 |
<span>置き換える文字列</span> |
ちょっと忘備録的要素が強いですが、jQueryでフォームのバリデーションなどをする時にも役立つと思います。
- 2014年04月06日日曜日
- :Naruhiko Wakai
コメントを残す