Reputation: 3730
Take the following example
<div id="blog">
<div class="postContent">
<img src="img.png" alt="Keep this one"/>
<img src="img.png" alt="REMOVE this one"/>
<img src="img.png" alt="REMOVE this one"/>
<img src="img.png" alt="REMOVE this one"/>
</div>
<div class="postContent">
<img src="img.png" alt="Keep this one"/>
<img src="img.png" alt="REMOVE this one"/>
<img src="img.png" alt="REMOVE this one"/>
<img src="img.png" alt="REMOVE this one"/>
</div>
<div class="postContent">
<img src="img.png" alt="Keep this one"/>
<img src="img.png" alt="REMOVE this one"/>
<img src="img.png" alt="REMOVE this one"/>
<img src="img.png" alt="REMOVE this one"/>
</div>
</div>
Obviously I want to remove the images where the alt is (albeit different in production) "REMOVE this one"
What I have tried:
$('#blog .postContent img').slice(1).remove(); // AND
$('#blog .postContent img').not(':first').remove();
Result:
<div id="blog">
<div class="postContent">
<img src="img.png" alt="Keep this one"/>
</div>
<div class="postContent">
</div>
<div class="postContent">
</div>
</div>
However my desired result is:
<div id="blog">
<div class="postContent">
<img src="img.png" alt="Keep this one"/>
</div>
<div class="postContent">
<img src="img.png" alt="Keep this one"/>
</div>
<div class="postContent">
<img src="img.png" alt="Keep this one"/>
</div>
</div>
I'm missing what I am sure should be very simple, will be very grateful for any pointers
Upvotes: 1
Views: 241
Reputation: 1956
try this.use first-of-type
$('#blog .postContent img').not('img:first-of-type').remove()
Upvotes: 1
Reputation: 16575
Pure CSS:
.postContent img:nth-child(n+2) {
display: none;
}
jQuery Version:
$('.postContent').each(function(){
$(this).children('img:nth-child(n+2)').remove();
});
Upvotes: 1
Reputation: 67207
Try to use :not()
selector along with :first-child
selector,
$('#blog .postContent img:not(:first-child)').remove();
Or you could use simple css
for this purpose,
#blog .postContent img:not(:first-child){
display:none;
}
Upvotes: 2