gabbar0x
gabbar0x

Reputation: 4266

jQuery replacing only one instance of .first()

Say I have something like this:

<div class="carousel-inner onebyone-carosel" id="carousel-inner">
    <div class="item">
        <!--Stuff-->
    </div>
</div>

<!--Same thing again-->

<div class="carousel-inner onebyone-carosel" id="carousel-inner">
    <div class="item">
        <!--Stuff-->
    </div>
</div>

Now, when I use $(".carousel-inner div:first").addClass('active');, the class active is added only the div of the first carousel-inner. The second one remains as it is.

Is this the expected behavior? Or am I missing something?

Upvotes: 0

Views: 88

Answers (3)

JackHasaKeyboard
JackHasaKeyboard

Reputation: 1675

The :first CSS selector is returning the first instance of a div element located within a div with the class of carousel-inner. AKA, the first instance of .carousel-inner div

If you want the first instance of a div within every instance of a .carousel-inner element use a child selector, :nth-child(1) or :first-child

Upvotes: 0

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11096

.carousel-inner div:first selects the first occurance of .carousel div ! You may use jquery find() for this purpose:

$(document).ready(function(){
$(".carousel-inner").find("div:first").addClass('active');
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner onebyone-carosel" id="carousel-inner">
    <div class="item">
        sdsd
    </div>
</div>

<!--Same thing again-->

<div class="carousel-inner onebyone-carosel" id="carousel-inner2">
    <div class="item">
        dfgdfg
    </div>
</div>

Upvotes: 1

Don
Don

Reputation: 1334

Yes, it would add it to first div only.

Do this:

$(".carousel-inner div:first-child").addClass('active');

Upvotes: 1

Related Questions