empty()メソッドとremove()メソッドの違い。
- empty()は中身を削除する。
- remove()はそのもの本体ごと削除する。
- remove([exp])でセレクターの条件にあったものだけ削除されます。
例:
html
- <h1>jQuery(empty and remove)</h1><ul><li id="first">1.Text</li>
- <li id="second">2.Text<b>Strong</b>TextText<i>Em</i></li>
- <li id="third">3.Text<b>Strong</b>Text</li>
- <li id="fourth">4.Text<i>i</i>TextText</li>
- </ul><form action=""><input id="btn1" type="button" value="empty">
- <input id="btn2" type="button" value="remove">
- <input id="btn3" type="button" value="remove(':has(em)')">
- <input id="btn4" type="button" value="remove(':contains("Strong" )')">
- </form>
- 1.Text
- 2.TextStrongTextTextEm
- 3.TextStrongText
- 4.TextiTextText
cssは分かりやすいように色付け(お好みで)
- li {
- background-color: lavender;
- border: 1px solid royalblue;
- height: auto;
- width : 400px;
- padding: 5px;
- }
- strong {
- background-color: seashell;
- border: 1px solid fuchsia;
- }
- em {
- background-color: beige;
- border: 1px solid chocolate;
- }
- i {
- background-color: lightsalmon;
- border: 1px solid tomato;
- }
jQuery部分
empty()とremove()とremove([exp])で変化を見ます
- jQuery(function() {
- //liにempty()を適用します
- $("#btn1").click(function() {
- $('li').empty();
- });
- //liにremove()を適用します
- $("#btn2").click(function() {
- $('li').remove();
- });
- //em要素が含まれるliにremove()が適用されます
- $("#btn3").click(function() {
- $('li').remove(':has(em)');
- });
- //文字列[Strong]が含まれるliにremove()が適用されます
- $("#btn4").click(function() {
- $('li').remove(':contains("Strong")');
- });
- });
初期状態
empty()を使用した場合
remove()を使用した場合
remove(':has(em)')を使用した場合
remove(':contains("Strong")')を使用した場合
0 件のコメント:
コメントを投稿