开发者

jquery how to remove a instance of a div if 2 are present?

开发者 https://www.devze.com 2023-02-22 05:16 出处:网络
this question sounds a bit confusing, but here is what i have: <div id=\"type2\"> <img class=\"profile-img\" src=\"75.jpg\">

this question sounds a bit confusing, but here is what i have:

<div id="type2">
<img class="profile-img" src="75.jpg">
</div>

after i click on something it becomes like this:

<div id="type2">
<img class="profile-img" src="75.jpg">
<img class="profile-img" src="76.jpg">
</div>

what i want is to remove the first img instance if two are present. basically to become:

<div id="type2">
<img class="profile-img" src="76.jpg">
</div>

i've tryed:

    if (item.lenght == 2) {
$('#type2').find('.profile-img:first'开发者_如何学JAVA).remove();
}

but it doesn't seem to work thanks

edit:

thanks all. this answer is what worked for me from shifty:

if ($('#type2').find('.profile-img').size() >= 2) {
$('#type2').find('.profile-img:first').remove();
}

i did misspelled the length but still didn't want to work :)


The code $('#type2').find('.profile-img:first').remove(); will definitely remove the first element with the class profile-img in the #type2 selector, so things are broken elsewhere.

Is it just because you've misspelled the length attribute in item.lenght?


this should work

if ($('#type2').find('.profile-img').size() >= 2) {
  $('#type2').find('.profile-img:first').remove();
}


This should work:

$('.profile-img','#type2').eq(0).remove();

or

$('.profile-img','#type2').first().remove();

or

$('#type2 .profile-img:first').remove();

or

$('.profile-img:first','#type2').remove();


Your way should work fine. I would guess the problem is the typo "lenght":

if (item.length == 2) {
    $('#type2').find('.profile-img:first').remove();
}

Assuming of course that item is defined and has a length of exactly 2.

0

精彩评论

暂无评论...
验证码 换一张
取 消