いちばん失敗した人決定戦

ボタンを押すと、それぞれの<label></label>の中の<img src = "sample.jpg" /> <br>を、1セットをのこして、あとは消すというのをやりたいのですが、うまくいきません。:gt(0)の部分を:not(:first)にしても無理でした。なので、根本的に、やり方がおかしいのかもしれないと思うので、アドバイスください。

$('label').children('img:gt(0)').remove('img');
要素の中の要素を指定して(1番目を除いて)、消すという考え方なのですが… 何が違うんでしょう。


[index.html]

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>TEST</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2 …

</head>
<body>

<script type="text/javascript">

$(function() {
$('button#img').click(function(){

$('label').children('img:gt(0)').remove('img');
$('label').children('br:gt(0)').remove('br');

});
});
</script>


<label>
<img src = "sample.jpg" /><br>
</label>

<label>
<img src = "sample.jpg" /><br>
<img src = "sample.jpg" /><br>
</label>

<label>
<img src = "sample.jpg" /><br>
<img src = "sample.jpg" /><br>
<img src = "sample.jpg" /><br>
</label>

<br>
<button id="img" type="button">削除</button>


</body>
</html>


[希望する出力結果] … <label></label>の中に<img src = "sample.jpg" /><br>が2つ以上ある部分は、removeで消されてる。

<label>
<img src = "sample.jpg" /><br>
</label>

<label>
<img src = "sample.jpg" /><br>
</label>

<label>
<img src = "sample.jpg" /><br>
</label>

A 回答 (2件)

あとはindexを使ってこれでもいいかも



$(function() {
$('button#img').click(function(){
$('label img').filter(function(){return $(this).closest('label').find('img').index(this)>0;}).next('br').remove().end().remove();
});
});
    • good
    • 1
この回答へのお礼

ありがとうございます。.filter()でも処理できるのですね。すごいです!!とても参考になります。

お礼日時:2017/06/30 15:28

$(function() {


$('button#img').click(function(){
$('label').each(function(){
$(this).find('img:gt(0)').next('br').remove().end().remove();
});
});
});
    • good
    • 1
この回答へのお礼

ありがとうございます。each()の使い方と、あと.next()は使ったことがなかったので、とても勉強になります。

お礼日時:2017/06/30 15:26

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!