zanderwar
zanderwar

Reputation: 3730

Remove all images but first within a div

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

Answers (3)

shu
shu

Reputation: 1956

try this.use first-of-type

$('#blog .postContent img').not('img:first-of-type').remove()

Upvotes: 1

Pedram
Pedram

Reputation: 16575

Pure CSS:

.postContent img:nth-child(n+2) {
  display: none;
}

jsFiddle Demo


jQuery Version:

$('.postContent').each(function(){
$(this).children('img:nth-child(n+2)').remove();
});

jsFiddle Demo

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to use :not() selector along with :first-child selector,

$('#blog .postContent img:not(:first-child)').remove();

DEMO

Or you could use simple css for this purpose,

#blog .postContent img:not(:first-child){
  display:none;
}

DEMO

Upvotes: 2

Related Questions