Sara Briccoli
Sara Briccoli

Reputation: 176

jQuery hide all images except first one in a generic way

I want to show only the first image and hide others, this is how HTML looks like:

<div class="slider-image">
  <img src="html.png" alt="Html" />
  <img src="css.png" alt="Css" />
  <img src="jquery.png" alt="jQuery" />
</div>

In this example I want to see html.png but I have to consider more images so I have to find a generic solution. I tried with:

$("div.slider-image").hide();
$("div.slider-image").eq(0).show();

but it shows every image, can someone help me?

Upvotes: 1

Views: 125

Answers (7)

Artur Noetzel
Artur Noetzel

Reputation: 453

Do you really need to use jQuery for this? You can achieve this with plain css:

.slider-image > img:not(:first-child) {
    display: none;
}

Upvotes: 1

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

You can try the below code. It's working perfectly. And image display in the center.

$('.slider-image img:not(:first-child)').hide();
.slider-image {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 10%;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<div class="slider-image">
    <img src="html.png" alt="Html" />
    <img src="css.png" alt="Css" />
    <img src="jquery.png" alt="jQuery" />
</div>

Upvotes: 0

EmreKalafat
EmreKalafat

Reputation: 106

$('.slider-image img:not(:first-child)').css('opacity':0);

it's not the right way but it's work @Anant Singh it's give to right answer but it's work for you

Upvotes: 0

Asfan Shaikh
Asfan Shaikh

Reputation: 769

You can use simple one line jQuery code...

$("div.slider-image img").eq(0).siblings('img').hide();

Upvotes: 0

Sagar Jajoriya
Sagar Jajoriya

Reputation: 2375

Try this:

$("div.slider-image img:not(:first-child)").hide();

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

use .not

Working snippet:

$('.slider-image img').not(':eq(0)').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider-image">
    <img src="html.png" alt="Html" />
    <img src="css.png" alt="Css" />
    <img src="jquery.png" alt="jQuery" />
</div>

Or use :not(:first-child)

Working snippet:-

$('.slider-image img:not(:first-child)').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider-image">
    <img src="html.png" alt="Html" />
    <img src="css.png" alt="Css" />
    <img src="jquery.png" alt="jQuery" />
</div>

Upvotes: 2

BhAvik Gajjar
BhAvik Gajjar

Reputation: 458

<div class="slider-image">
            <img src="html.png" alt="Html" />
            <img src="css.png" alt="Css" class="hide_img"/>
            <img src="jquery.png" alt="jQuery" class="hide_img" />
        </div>

In script

$("div.slider-image .hide_img").hide();

Upvotes: 0

Related Questions